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
- TemplateTag to Split a List into Uniform Chunks by cmcavoy 5 years, 2 months ago
- BetterForm with fieldsets and row_attrs by carljm 4 years, 3 months ago
- Breadcrumbs for flatpages by jca 5 years, 5 months ago
- SuperChoices by willhardy 4 years, 6 months ago
- Twitter template tags and filters by moxypark 2 years, 9 months ago
Comments