Django - iterate number in for loop of a template

2019-01-05 11:57发布

问题:

I have the following for loop in my django template displaying days. I wonder, whether it's possible to iterate a number (in the below case i) in a loop. Or do I have to store it in the database and then query it in form of days.day_number?

{% for days in days_list %}
    <h2># Day {{ i }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}

回答1:

Django provides it you can use {{ forloop.counter }} index start at 1 or {{ forloop.counter0 }} index start at 0.

More info at Django template forloop

Just to add quick help here rather than going to django doc.

In template you can do

...
{% for item in item_list %}
    {{ forloop.counter }} {# starting index 1 #}
    {{ forloop.counter0 }} {# starting index 0 #}

    {# do your stuff #}
{% endfor %}


回答2:

Also one can use this:

{% if forloop.first %}

or

{% if forloop.last %}


标签: