3

In a Django template, I want to create a for loop that iterates through a list. During that loop, I also want to be able to use the iteration number of the loop.

For example, if some_list has 4 elements, then:

{% for o in some_list %}
    # Print out the iteration number
{% endfor %}

Should print out the following:

>> 0
>> 1
>> 2
>> 3

How can I do this?

Karnivaurus
  • 22,823
  • 57
  • 147
  • 247
  • 1
    possible duplicate of [Django - iterate number in for loop of a template](http://stackoverflow.com/questions/11481499/django-iterate-number-in-for-loop-of-a-template) – szymanskilukasz Jul 03 '14 at 16:20

1 Answers1

6

See the docs for the for tag. To get the loop index use {{ forloop.counter0 }} inside the block.

davidism
  • 121,510
  • 29
  • 395
  • 339