The for loop is a fundamental control structure in Jinja2 used to iterate over sequences, such as lists, tuples, or dictionaries. It’s the primary way to display collections of data, making it a crucial tool for rendering dynamic content like lists, tables, and product catalogs. You can also use the for loop to filter data directly within the template.n
nn
Basic for Loop Syntax
nA basic for loop iterates through each item in a sequence, assigning each item to a temporary variable for use inside the loop. The loop is defined by the {% for ... %} and {% endfor %} tags.n
Syntax
n
<ul>n{% for user in users %}n <li>{{ user.name }}</li>n{% endfor %}n</ul>
nIn this example, the loop iterates over a list named users. In each iteration, the current user object is assigned to the user variable, and its name is printed inside a list item.nn
nn
Looping Over Different Data Structures
nThe for loop can handle various data types.n
Iterating a Dictionary
nWhen looping over a dictionary, you can access keys, values, or both.n
- n
- Looping over keys (default):n
{% for key in my_dict %}n <p>Key: {{ key }}</p>n{% endfor %}n
- Looping over values:n
{% for value in my_dict.values() %}n <p>Value: {{ value }}</p>n{% endfor %}n
- Looping over key-value pairs: This is the most common approach for dictionaries.n
{% for key, value in my_dict.items() %}n <p>{{ key }}: {{ value }}</p>n{% endfor %}n
n
n
n
nn
nn
Filtering with if within the Loop
nYou can filter the items being iterated over by adding an if clause at the end of the for statement. This is a concise way to display only the items that meet a certain condition.n
Syntax
n
<ul>n{% for user in users if user.is_active %}n <li>{{ user.name }}</li>n{% endfor %}n</ul>
nThis loop will only render a list item for users whose is_active attribute is True, effectively filtering the list on the fly.nn
nn
The loop Variable
nInside a for loop, Jinja2 provides a special variable called loop that contains useful information about the current iteration.n
- n
loop.index: The current iteration number (1-based).loop.index0: The current iteration number (0-based).loop.first: A boolean that isTruefor the first iteration.loop.last: A boolean that isTruefor the last iteration.loop.revindex: The number of items from the end of the list (1-based).loop.length: The total number of items in the sequence.
n
n
n
n
n
n
nA common use of loop.first is to add a special class to the first item.n
<ul class="product-list">n{% for product in products %}n <li class="{% if loop.first %}first-item{% endif %}">n {{ product.name }}n </li>n{% endfor %}n</ul>
nn
nn
The else Block
nA for loop can have an optional else block that is executed if the sequence being iterated over is empty. This is a great way to handle empty data gracefully.n
<div class="user-list">n{% for user in active_users %}n <p>User: {{ user.name }}</p>n{% else %}n <p>No active users found.</p>n{% endfor %}n</div>
nn
nn
Full Demonstration
nHere is a complete example showing different ways to use the for loop.n
Jinja2 Template (inventory.html)
n
<!DOCTYPE html>n<html lang="en">n<head>n <title>Store Inventory</title>n</head>n<body>nn <h1>All Products</h1>n <ul class="product-list">n {% for product in products %}n <li>{{ loop.index }}. {{ product.name }} - ${{ product.price }}</li>n {% endfor %}n </ul>nn <h1>In-Stock Products</h1>n <ul class="in-stock-list">n {% for product in products if product.stock > 0 %}n <li>{{ product.name }} ({{ product.stock }} available)</li>n {% else %}n <li>No products are currently in stock.</li>n {% endfor %}n </ul>n n <h1>Product Categories</h1>n <ul>n {% for category, items in inventory.items() %}n <li><strong>{{ category|title }}</strong>: {{ items|join(', ') }}</li>n {% endfor %}n </ul>nn</body>n</html>
n
Python Code to Render the Template
n
from jinja2 import Environment, FileSystemLoadernndata = {n 'products': [n {'name': 'Laptop', 'price': 1200, 'stock': 5},n {'name': 'Mouse', 'price': 25, 'stock': 0},n {'name': 'Keyboard', 'price': 75, 'stock': 12},n ],n 'inventory': {n 'electronics': ['Laptop', 'Mouse', 'Keyboard'],n 'office': ['Notebook', 'Pen']n }n}nnenv = Environment(loader=FileSystemLoader('.'))ntemplate = env.get_template('inventory.html')nrendered_html = template.render(data)nnprint(rendered_html)
n
Rendered HTML Output
n
<!DOCTYPE html>n<html lang="en">n<head>n <title>Store Inventory</title>n</head>n<body>nn <h1>All Products</h1>n <ul class="product-list">n n <li>1. Laptop - $1200</li>n n <li>2. Mouse - $25</li>n n <li>3. Keyboard - $75</li>n n </ul>nn <h1>In-Stock Products</h1>n <ul class="in-stock-list">n n <li>Laptop (5 available)</li>n n <li>Keyboard (12 available)</li>n n </ul>n n <h1>Product Categories</h1>n <ul>n n <li><strong>Electronics</strong>: Laptop, Mouse, Keyboard</li>n n <li><strong>Office</strong>: Notebook, Pen</li>n n </ul>nn</body>n</html>
n
n
