from django.template import Library
register = Library()
@register.filter
def columnsacross(list, n):
"""
Divide list into (n) of columns going across
Example:
{% for column in object_list %}
{% for item in column %}
- {{ item }}
{% endfor %}
{% endfor %}
>>> list = range(1, 11)
>>> columnsacross(list, 4)
[[1, 5, 9], [2, 6, 10], [3, 7], [4, 8]]
>>> columnsacross(list, 3)
[[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]
"""
try:
n = int(n)
list = list(list)
except (ValueError, TypeError):
return [list]
return [list[i::n] for i in range(n)]
if __name__ == "__main__":
import doctest
doctest.testmod()