2

I need to use loop-counter in a pythonic for-loop in an html template file. How do I do it? Following is a piece of code that would provide a better idea of what I'm trying to say.

{% for idx, keyword in enumerate(keywords) %}

...do something with idx

{% endfor %}

Here, 'keywords' is a list that I get through the Django dictionary. "Could not parse the remainder: '(keywords)' from 'enumerate(keywords)'" is what I get for the first line. Any suggestions would be appreciated. Thanks!

Vikrant
  • 101
  • 3
  • 12

2 Answers2

5

try

{% for keyword in keywords %}

    {{ forloop.counter }} # 1 based
    {{ forloop.counter0 }} # 0 based

{% endfor %}

the documentation here has all the options that are available inside for loops

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for

Stuart Leigh
  • 826
  • 4
  • 6
1

To have the same index as in enumerate, use forloop.counter0. There is also forloop.counter for 1-based indexing.

{% for keyword in keywords %}
    {{ forloop.counter0 }}
{% endfor %}

Check forloop.counter0.

Tim Zimmermann
  • 6,132
  • 3
  • 30
  • 36