So here\'s my problem: I\'ve got a bunch of instances of a class. I would like to have a sort of table of these instance objects, so that there is a maximum of six in every
I would recommend to add a custom tag as_chunk
. I think it makes the code prettier and more readable.
# app/templatetags/my_tags.py
from math import ceil
from django import template
register = template.Library()
@register.filter
def as_chunks(lst, chunk_size):
limit = ceil(len(lst) / chunk_size)
for idx in range(limit):
yield lst[chunk_size * idx : chunk_size * (idx + 1)]
# app/templates/your-template.html
{% load my_tags %}
...
{% for chunk in elements|as_chunk:6 %}
{% for element in chunk %}
{{ element.name }}
{% endfor %}
{% endfor %}
...