43๐
You want the forloop.counter template variable.
The for loop sets a number of variables available within the loop:
forloop.counter The current iteration of the loop (1-indexed)
So your code would look like:
{% for sport in sports %}
<p>{{forloop.counter}}. {{ sport }}</p>
{% endfor %}
Of course, for simply displaying the data as you do in your question, the easier way is just to show the items in an ordered list, and the browser will do the numbering for you:
<ol>
{% for sport in sports %}
<li>{{ sport }}</li>
{% endfor %}
</ol>
4๐
The answer from @nrabinowitz is a good solution if you want to use it in a template. But I think you were asking to do that from a view.
The best way to get the index and value from a list is using the enumerate
function, like this:
>>> sports = ['football', 'basketball', 'soccer']
>>> for i,sport in enumerate(sports):
... print "%d. %s" % (i, sport)
0. football
1. basketball
2. soccer
Or, if you want a 1-based index:
>>> for i,sport in enumerate(sports):
... print "%d. %s" % (i+1, sport)
1. football
2. basketball
3. soccer
- Are middlewares an implementation of the Decorator pattern?
- How to get the previous URL in Django
- Tutorials on writing custom Django widgets?
- Format of timesince filter
1๐
courtesy of the answer above
If someone needs to use a condition of the loop iteration count, he can use this block of code.
2
is used for illustration of an integer
.
{% if forloop.counter == 2 %}
do something what you want for second iteration
{% endfor %}
- Django object is not iterable using serializers.serialize
- Django-mutant creating models in django-admin
- Django: duplicates when filtering on many to many field
- Creating custom Exceptions that Django reacts to
- Generating dynamic CSS