django forloop.counter operation

时间:2011-03-11 17:27:38

标签: django for-loop django-templates

我想知道如何在django中复制它:

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

如果它是“1”,我如何检查forloop计数器?

1 个答案:

答案 0 :(得分:34)

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

这相当于:

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

参考:Django docs