Home > front end >  Add html code if the element is first in query - Django
Add html code if the element is first in query - Django

Time:01-08

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 >
  [...]
</div>
{% endfor %}

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

CodePudding user response:

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

{% for obj in query %}
<div >
  [...]
</div>
{% endfor %}

The forloop.first will return:

True if this is the first time through the loop

CodePudding user response:

You can use forloop.counter like this:

{% for obj in query %}
<div >
  [...]
</div>
{% endfor %}

forloop.counter is 1 index based counter used to store current index of the loop.

  •  Tags:  
  • Related