How to use for loops in Django template tags

A Django template is a text document similar to HTML with added Jinja syntax. The syntax of the Django template language involves four constructs: {{ }} and {% %}.

In this shot, we will look at how to use a for loop in Django templates.

The for template in Django is commonly used to loop through lists or dictionaries, making the item being looped over available in a context variable.

Syntax

{% for i in _list %}
{% endfor %}

Code

The code below shows how the for template is used in Django.

<ul>
{% for person in person_list %}
    <li>{{ person.name }}</li>
    <li>{{ person.age }}</li>
{% endfor %}
</ul>

Explanation

In the code above, the array person_list is iterated over and each element in the array is available inside the loop in the person variable. The person object’s name and age is accessed inside the template context and used to create a list item using <li>. This is repeated for each element in person_list.

To iterate over a list in reverse, add reverse at the end of the for loop statement like so: {% for obj in list reversed %}.

Free Resources