1👍
If I understand correctly you need to close your row
after 3 objects.
To do this you should take a look at forloop.counter
template tag and divisibleby
filter in Django documentation about built-in template tags.
👤Luca
0👍
It seems that you want to split a list into equally sized chunks in django templates.
The following snippet would help.
Templatetag code:
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 code:
{% for chunk in images|chunks:3 %}
<div class="row">
{% for image in chunk %}
<div class="col-md-4">
{{image}}
</div>
{% endfor %}
</div>
{% endfor %}
- [Answer]-How to run Django views from a script?
- [Answer]-Urls with ".html" suffix in FlatPages
- [Answer]-Accessing a full object through a relation in Django
- [Answer]-How can I override an inherited container in Django templates?
Source:stackexchange.com