Jinja Basic Assignments
n
Jinja2 allows you to assign values to variables inside your templates using the set statement. This is a simple and effective way to store data, whether it’s a static value, a result from a function call, or a more complex data structure. Assignments are useful for improving readability by giving a meaningful name to a value that will be used multiple times.
nn
How It Works
n
The set statement works just like a variable assignment in a regular programming language. You use the syntax `{% set variable_name = value %}`. You can assign basic data types, lists, dictionaries, or the result of a function or macro call. It’s also possible to unpack values from a tuple or list into multiple variables at once.
nn
Basic Usage
n
{% set navigation = [('index.html', 'Index'), ('about.html', 'About')] %}n{% set key, value = call_something() %}
n
In this example, the first line assigns a list of tuples to a variable named navigation. This is perfect for defining a menu or a set of links. The second line shows how to unpack a value returned from a function call into two separate variables, `key` and `value`.
nn
nn
Scope and Importance
n
Assignments made at the top level of a template (outside of any blocks, macros, or loops) have a special significance. They are “exported” from the template and can be imported and used by other templates, just like top-level macros. This allows you to define reusable variables and configurations in a single place and share them across your project, ensuring consistency and making your templates more modular and maintainable.
nn
n
n
