How to display index during list iteration using Django?

I pass the list to the view. My array looks like this: [football, basketball, soccer]. In my opinion, I would like to show something like this:

1. football
2. basketball
3. soccer

This means that I will have to iterate over the list that is passed to the array, do a for loop for the elements. How can I do this in a template file?

For each element, I will need to get its index and add 1 to it. Now I do not know how to do this in representations. One of the ways I thought about this is to make a dictionary, for example, {'1', 'football': '2', 'basketball': '3', 'soccer'}but since I already have the data in list format, I would prefer not to convert it.

+5
source share
2 answers

forloop.counter.

for , :

forloop.counter (1-)

, :

{% for sport in sports %}
    <p>{{forloop.counter}}. {{ sport }}</p>
{% endfor %}

, , , , :

<ol>
{% for sport in sports %}
    <li>{{ sport }}</li>
{% endfor %}
</ol>
+21

@nrabinowitz - , . , .

- enumerate, :

>>> sports = ['football', 'basketball', 'soccer']
>>> for i,sport in enumerate(sports):
...     print "%d. %s" % (i, sport)
0. football
1. basketball
2. soccer

, 1:

>>> for i,sport in enumerate(sports):
...     print "%d. %s" % (i+1, sport)
1. football
2. basketball
3. soccer
+3

All Articles