for Template Tag
Example
Loop through a list and display the values
<ul>
{% for x in fruits %}
<li>{{ x }}</li>
{% endfor %}
</ul>
Run Example »
Definition and Usage
The for
tag allows you to iterate over items in an object.
Objects can be array-like objects like a Python list or object-like objects like a Python dictionary:
Example
Loop through dictionary and display the keys and values:
{% for x, y in mycar.items %}
<p>The {{ x }} is {{ y }}.</p>
{% endfor %}
Run Example »
Syntax
{% for item in object %}
...
{% endfor %}
Parameters
Value | Description |
---|---|
item | Required. Variable name(s) that represents the item(s) of the iterable object. |
object | Required. An iterable object. |
Built-in for Variables
There are some built-in variables you can use inside for loops:
Variable | Description | |
---|---|---|
forloop.counter | The current iteration, starting at 1. | Example » |
forloop.counter0 | The current iteration, starting at 0. | Example » |
forloop.first | Check if this iteration is the first iteration. | Example » |
forloop.last | Check if this iteration is the last iteration. | Example » |
forloop.parentloop | Refers to the parent loop. | Example » |
forloop.revcounter | The current iteration, counting backwords, ending at 1. | Example » |
forloop.revcounter0 | The current iteration, counting backwords, ending at 0. | Example » |