Often used to loop through querysets, but it can be used to loop through any iterable.
Looping through a Queryset
<ul> {% for joke in joke_list %} <li>{{ joke.question }}</li> {% endfor %} </ul>
Looping through a Dictionary
<ol> {% for item, remaining in inventory.items %} <li>{{ item }}: {{ remaining }}</li> {% endfor %} </ol>
Looping through a List
<ol> {% for fruit in fruits %} <li>{{ fruit }}</li> {% endfor %} </ol>
To loop through a list in reverse order, used reversed
:
Looping through a List in Reverse
<ol> {% for fruit in fruits reversed %} <li>{{ fruit }}</li> {% endfor %} </ol>
Empty Iterables
Sometimes, you won’t be sure that your iterable contains any values. This is especially true with querysets. In such case, you can use the empty
tag to output a message indicating that no records were found. For example:
<ul> {% for joke in joke_list %} <li>{{ joke.question }}</li> {% empty %} <li>Sorry, there are no jokes.</li> {% endfor %} </ul>
Looping through a List displaying a Counter
<table> {% for fruit in fruits %} <tr> <td>{{ forloop.counter }}</td> <td>{{ fruit }}</td> </tr> {% endfor %} </table>
Variables Available in for
Loops
The following variables are available within for
loops:
forloop.counter
– The current iteration starting with1
.forloop.counter0
– The current iteration starting with0
.forloop.revcounter
– The iteration’s position from the end. For the last iteration, this will be1
.forloop.revcounter0
– The remaining iterations. For the last iteration, this will be0
.forloop.first
–True
for the first iteration.forloop.last
–True
for the last iteration.forloop.parentloop
– The current loop’s parent loop.
Commentary
Also see the
ifchanged
tag.