1👍
✅
Trying to perform this logic in the template isn’t ideal, as you have discovered. I would suggest you do it in the view function. Something along these lines:
# Handy function to split a list into equal sized groups,
# See http://stackoverflow.com/a/434328/3955830
def chunker(seq, size):
return (seq[pos:pos + size] for pos in xrange(0, len(seq), size))
# Split images into groups of three
image_groups = chunker(images, 3)
# Pass image_groups to your template context.
# If in a class based view then you can do this in the
# get_context_data() method.
Then in the template, things are much simpler:
{% for group in image_groups %}
<div class="item {% if forloop.first %}active{% endif %}">
<div class="gallery row">
<div class="col-xs-12 col-sm-12">
{% for image in group %}
<a class="thumbnail" rel="#image-{{ image.id }}" title="{{ image.description }}" href="{{ image.file.url }}">
<img class="img-responsive" src="{{ MEDIA_URL }}{% thumbnail image.file 200 200 %}"></a>
{% endfor %}
</div>
</div>
</div>
{% endfor %}
Source:stackexchange.com