Search code examples
djangotemplatetags

Add html code if the element is first in query - Django


In the Bootstrap slider, the first element has the value "active", how to check and add this value to the html code for the queryset, if element is first.

Example (which is not working):

{% for obj in query %}
<div class="carousel-item {% if query|first %}active{% endif %}">
  [...]
</div>
{% endfor %}

*this gives activity for all items, not just the first. Expected result is only for first.


Solution

  • You can work with forloop.first [Django-doc] to check if it is the first element, so:

    {% for obj in query %}
    <div class="carousel-item{% if forloop.first %} active{% endif %}">
      [...]
    </div>
    {% endfor %}

    The forloop.first will return:

    True if this is the first time through the loop