Jinja Literal Expression: Dictionaries
n
{key: value}). Keys must be unique and always have exactly one value. While dictionaries are not as frequently used in templates as lists, they are valuable in specific cases, such as with the xmlattr() filter.nn
nn
How It Works
nDictionaries provide a way to store data in a non-sequential, key-based manner. This allows you to retrieve a specific value by referencing its key, which is more intuitive than using a numerical index like with lists. The keys can be strings or numbers, but the values can be any data type, including other dictionaries or lists. Dictionaries are particularly useful when the data structure you are working with has named attributes or properties.n
Syntax
n
{{ {'key': 'value', 'another_key': 42} }}n{% set my_dict = {'user': 'admin', 'is_active': True} %}
nn
nn
Demonstration with Code Samples
nHere are some practical examples of how to use dictionary literals in a Jinja2 application.n
1. Using a Dictionary in a `for` Loop
nYou can iterate over a dictionary to display both its keys and values, which is useful for creating tables or dynamic content.nnJinja2 Templaten
{% set user_info = {n 'name': 'John Doe',n 'age': 30,n 'city': 'New York'n} %}n<table>n {% for key, value in user_info.items() %}n <tr>n <td>{{ key|capitalize }}:</td>n <td>{{ value }}</td>n </tr>n {% endfor %}n</table>
nExplanation: The template uses the .items() method to loop through the key-value pairs of the user_info dictionary. It then displays each pair in an HTML table row.nn
nn
2. Using a Dictionary with the `xmlattr()` Filter
nThe xmlattr() filter is a prime example of a function that uses a dictionary. It takes a dictionary of attributes and their values and converts them into a valid HTML/XML attribute string.nnJinja2 Templaten
{% set my_attributes = {n 'id': 'main-link',n 'class': 'btn btn-primary',n 'data-toggle': 'modal'n} %}n<a href="#" {{ my_attributes|xmlattr }}>Click Me</a>
nExplanation: The my_attributes dictionary is passed to the xmlattr() filter. This generates the HTML attributes id="main-link" class="btn btn-primary" data-toggle="modal", which are then correctly inserted into the <a> tag.nn
