"""
Template tags for working with lists.
You'll use these in templates thusly::
{% load listutil %}
{% for sublist in mylist|anticollate:"3" %}
{% for item in mylist %}
do something with {{ item }}
{% endfor %}
{% endfor %}
"""
from django import template
register = template.Library()
@register.filter
def anticollate(thelist, n):
"""
Break a list into ``n`` pieces. Some lists (at the beginning) may be larger than the rest if
the list doesn't break cleanly. That is::
>>> l=range(10)
>>> anticollate(l,3)
[[0, 3, 6, 9], [1, 4, 7], [2, 5, 8]]
>>> anticollate(l,4)
[[0, 4, 8], [1, 5, 9], [2, 6], [3, 7]]
>>> anticollate(l,5)
[[0, 5], [1, 6], [2, 7], [3, 8], [4, 9]]
"""
try:
n = int(n)
thelist = list(thelist)
except (ValueError, TypeError):
return [thelist]
return [[thelist[j] for j in range(len(thelist)) if j%n==i] for i in range(n)]
Comments