Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display index during list iteration with Django?

Tags:

python

django

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.

like image 637
egidra Avatar asked Nov 10 '11 23:11

egidra


2 Answers

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>
like image 187
nrabinowitz Avatar answered Sep 27 '22 17:09

nrabinowitz


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 %}
like image 26
Shamsul Arefin Sajib Avatar answered Sep 27 '22 16:09

Shamsul Arefin Sajib