Chunks template filter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# templatetags file
from django import template

register = template.Library()

@register.filter(name='chunks')
def chunks(iterable, chunk_size):
    if not hasattr(iterable, '__iter__'):
        # can't use "return" and "yield" in the same function
        yield iterable
    else:
        i = 0
        chunk = []
        for item in iterable:
            chunk.append(item)
            i += 1
            if not i % chunk_size:
                yield chunk
                chunk = []
        if chunk:
            # some items will remain which haven't been yielded yet,
            # unless len(iterable) is divisible by chunk_size
            yield chunk

# template
    <table align="center" width="100%">
        {% for chunk in images|chunks:3 %}
            <tr>
                {% for image in chunk %}
                    <td align="center" valign="bottom">
                        <img src="{{ image.thumb }}" alt="{{ image.name }}"/>
                    </td>
                {% endfor %}
            </tr>
            <tr> 
                {% for image in chunk %}
                    <td align="center">
                        {{ image.name }}<br/>
                        {{ image.description }}
                    </td>
                {% endfor %}
            </tr>
        {% endfor %}
    </table>
 

More like this

  1. TemplateTag to Split a List into Uniform Chunks by cmcavoy 6 years, 1 month ago
  2. Template filter to get each attribute value in an iterable by strangefeatures 2 years, 1 month ago
  3. ImageMagick commands from Django Templates by cogat 4 years, 12 months ago
  4. partition template filters by SmileyChris 6 years, 7 months ago
  5. Breadcrumbs for flatpages by jca 6 years, 4 months ago

Comments

(Forgotten your password?)