I am passing a list to a view. My array looks like this: [football, basketball, soccer]
. In my view, I would like to display something like this:
1. football
2. basketball
3. soccer
This means that I would have to iterate through the list that is passed to the array, do a for loop on the elements. How would I do this in the template file?
For each element, I would have to get its index and add 1 to it. Now, I have no idea how to do this in the views. One way I thought about doing this would be to make a dictionary, like so, {'1', 'football': '2', 'basketball': '3', 'soccer'}
, but since I already have the data in a list format, I would rather not convert it.
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>
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With