Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django forloop.counter operation

I would like to know how to replicate this in django:

for photo in gallery
    if counter is 1 
        then use this photo
     endif
endfor

how do I check the forloop counter if it is "1"?

like image 979
Fel Avatar asked Mar 11 '11 17:03

Fel


People also ask

What is Forloop counter in Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.17-Sept-2021.

What does Forloop counter print?

counter indicates how many times the for tag has gone through its loop.

What is forloop last?

forloop.Allows you to test if the loop is on its last iteration.


1 Answers

{% for photo in gallery %}
    {% if forloop.counter == 1 %}
       Do something with {{ photo }}.
    {% endif %}
{% endfor %}

this is equivalent to:

{% for photo in gallery %}
    {% if forloop.first %}
       Do something with {{ photo }}.
    {% endif %}
{% endfor %}

Reference: Django docs

like image 84
Shawn Chin Avatar answered Oct 12 '22 08:10

Shawn Chin