Introduction to Loops in Jinja
Jinja is a modern and designer-friendly templating language for Python, modeled after Django's templates. It is easy to learn and adaptable to various backend frameworks. A core feature of Jinja is the ability to use loops and iterate over data structures. In this article, we'll explore how to use loops in Jinja templates with clear examples.
Basic Loop Syntax
Jinja uses familiar syntax to Python developers. To create a loop in Jinja, you use the for
statement inside a template.
{% for item in list %}
{{ item }}
{% endfor %}
In this example, list
is a sequence like a list or a tuple, and item
is the variable that represents each element on each iteration of the loop.
Example with Simple List
Let's expand on the basic example with a concrete implementation:
from jinja2 import Template
# Our data
items = ["apple", "banana", "cherry"]
# Our template
template = Template("""
{{ item }}""")
# Render the template with the data
rendered = template.render(items=items)
print(rendered)
When you run this Python code, it will output:
<ul>
<li>apple</li>
<li>banana</li>
<li>cherry</li>
</ul>
Looping Over a Dictionary
Jinja allows you to loop over a dictionary, where you can use both keys and values.
{% for key, value in dictionary.items() %}
{{ key }}: {{ value }}
{% endfor %}
Here's how you might implement it with data:
# Our data
dictionary = {"name": "John", "age": 25, "city": "New York"}
# Our template
template = Template("""
{{ key }}: {{ value }}""")
# Render the template with the data
rendered = template.render(dictionary=dictionary)
print(rendered)
And this will produce:
<ul>
<li>name: John</li>
<li>age: 25</li>
<li>city: New York</li>
</ul>
Using Loop Variables
Jinja provides several special variables within loop constructs:
loop.index
: The current iteration of the loop (1 indexed)loop.index0
: The current iteration of the loop (0 indexed)loop.revindex
: The number of iterations from the end (1 indexed)loop.revindex0
: The number of iterations from the end (0 indexed)loop.first
:True
if current iteration is the firstloop.last
:True
if current iteration is the last
{% for item in list %}
{% if loop.first %}
First: {{ item }}
{% elif loop.last %}
Last: {{ item }}
{% else %}
{{ item }} is at position {{ loop.index }}
{% endif %}
{% endfor %}
Conclusion
Loops in Jinja provide a powerful way to iterate over sequences and can be combined with conditional statements to build dynamic content templates. By using the examples above, you can get started with creating efficient, dynamic templates in Jinja.