Aswin Murugesh
Aswin Murugesh

Reputation: 11070

Align dynamic number of images django templates

I have a django template that gets a set of images. The number of images varies. I want to align it in the template file, like 3 images per line. Normal displaying of the image does not align it. creating a

<div class="col-md-4">
</div>

for each image misformats after 3 images. How do I acquire this, either using django itself, or in bootstrap?

Upvotes: 0

Views: 704

Answers (2)

Leonardo.Z
Leonardo.Z

Reputation: 9781

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 %}

Upvotes: 0

Luca
Luca

Reputation: 1118

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.

Upvotes: 1

Related Questions