Jinja Control Structure: for Loop with Dictionaries
n
for loop is a versatile control structure in Jinja that allows you to iterate over various data types, including dictionaries. As variables in templates retain their object properties, it is possible to iterate over containers like a `dict` to access its keys and values. This is essential for rendering dynamic content from structured, key-value data.nn
nn
n
How It Works
nWhen you loop over a dictionary, you can access both the key and the value for each item by using the dictionary’s .items() method. This method returns a list of key-value tuples, allowing you to unpack each pair directly into two variables within the loop. The loop continues until all key-value pairs in the dictionary have been processed.n
Syntax
n
{% for key, value in my_dict.items() %}n <!-- Code to repeat for each key-value pair -->n{% endfor %}
nn
nn
n
Demonstration with Code Samples
nHere are some practical examples of how to use the `for` loop to iterate over a dictionary in a Jinja2 application.n
1. Basic Dictionary Iteration
nThis is a common use of the `for` loop for dictionaries, used to generate a description list (<dl>) from key-value pairs, as in the example below.nnJinja2 Templaten
{% set my_dict = {'user': 'admin', 'is_active': True, 'last_login': '2023-10-27'} %}n<dl>n{% for key, value in my_dict.items() %}n <dt>{{ key|e }}</dt>n <dd>{{ value|e }}</dd>n{% endfor %}n</dl>
nExplanation: This template iterates through the key-value pairs of the `my_dict` dictionary using the .items() method. It then uses the `key` and `value` variables to create a description term (<dt>) and description details (<dd>) for each pair. The `|e` filter ensures that the output is safely escaped to prevent security vulnerabilities.nn
nn
n
2. Using Dictionary Items in a Table
nYou can also use a dictionary loop to dynamically create a table of information, which is a common pattern for displaying user profiles or product details.nnJinja2 Templaten
{% set user_profile = {'id': 101, 'username': 'jdoe', 'email': 'jdoe@example.com'} %}n<table>n <thead><tr><th>Key</th><th>Value</th></tr></thead>n <tbody>n {% for key, value in user_profile.items() %}n <tr>n <td>{{ key|capitalize }}</td>n <td>{{ value }}</td>n </tr>n {% endfor %}n </tbody>n</table>
nExplanation: This loop iterates over the `user_profile` dictionary. The `key` and `value` variables are used to populate the cells of a table row. The `|capitalize` filter is used to format the key for display.nn
n
