Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - iterate number in for loop of a template

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 %}
like image 938
orschiro Avatar asked Jul 14 '12 06:07

orschiro


3 Answers

Django provides it. You can use either:

  • {{ forloop.counter }} index starts at 1.
  • {{ forloop.counter0 }} index starts at 0.

In template, you can do:

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

    # do your stuff
{% endfor %}

More info at: for | Built-in template tags and filters | Django documentation

like image 183
Rohan Avatar answered Nov 15 '22 03:11

Rohan


Also one can use this:

{% if forloop.first %}

or

{% if forloop.last %}
like image 140
JMJ Avatar answered Nov 15 '22 03:11

JMJ


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

or if you want to start from 0

{% for days in days_list %}
        <h2># Day {{ forloop.counter0 }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}
like image 14
Ahmed Elgammudi Avatar answered Nov 15 '22 05:11

Ahmed Elgammudi