October 2018
Intermediate to advanced
332 pages
8h 9m
English
We can use loops in Jinja to iterate over any list or generator function, as follows:
{% for post in posts %}
<div>
<h1>{{ post.title }}</h1>
<p>{{ post.text | safe }}</p>
</div>
{% endfor %}
Loops and if statements can be combined to mimic the break functionality in Python loops. In this example, the loop will only use the post if post.text is not None:
{% for post in posts if post.text %}
<div>
<h1>{{ post.title }}</h1>
<p>{{ post.text | safe }}</p>
</div>
{% endfor %}
Inside the loop, you have access to a special variable called loop, which gives you access to information about the for loop. For example, if we want to know the current index of the current loop to emulate the enumerate function in Python, we can use the index ...