Search code examples
djangodjango-templatesdjango-template-filters

Django template - for loop and then if statement


I have this loop:

<div class="product-gallery-preview order-sm-2">
                            {% for images in Artikel.productimages_set.all %}
                            {% if images.Position == 1 %}
                                <div class="product-gallery-preview-item active" id="gallery{{ images.Position }}">
                            {% else %}
                                <div class="product-gallery-preview-item" id="gallery{{ images.Position }}">

the problem is that all div classes are active I think because it's true for the first picture which is found. Is it possible to go in the loop check all pictures if it is in Position 1 and just output the div box I tried to print?


Solution

  • You can use forloop.counter...

    {% if forloop.counter == 1 %}
      <div class="product-gallery-preview-item active" id="gallery{{ images.Position }}">
    {% else %}
      ....
    {% endif %}