Login

Chunks template filter

Author:
oggy
Posted:
October 3, 2008
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

A simple filter which divides an iterable (list, tupe, string, etc) in chunks, which can then be iterated over separately. A sample of the filter usage is given: a gallery template in which I needed to display images in a table, three images per row, one row for images followed by one row for their descriptions.

 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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.