python / beginner
Snippet
Iterating through Data in Templates
The {% for %} tag allows you to loop over items in a collection, with an optional {% empty %} block that executes if the list is empty.
snippet.py
1
2
3
4
5
6
7
<ul>{% for item in item_list %}<li>{{ item.name }}</li>{% empty %}<li>No items available.</li>{% endfor %}</ul>
django
Breakdown
1
{% for item in item_list %}
Starts a loop that iterates through each element in the 'item_list' variable.
2
{{ item.name }}
Renders the name attribute of the current item in the iteration.
3
{% empty %}
Provides fallback content if the list is empty or undefined.
4
{% endfor %}
Ends the loop block.