Understanding Variables
n
Variables are the core of any dynamic templating language. In Jinja, template variables are placeholders that are filled with data from a context dictionary passed to the template by the application. This allows you to separate your application’s logic and data from your template’s presentation, which is a fundamental principle of modern web development.
nn
Accessing Variables and Attributes
n
You can access variables directly within your templates, as long as they have been passed in by the application. Variables may have attributes or elements on them, which you can access in a couple of different ways. What attributes a variable has depends heavily on the application providing that variable to the template.
n
You can use a dot (.) to access attributes of a variable in addition to the standard Python getitem subscript syntax ([]). These two methods do the same thing and can often be used interchangeably.
nn
{# Both of these lines do the same thing #}n{{ foo.bar }}n{{ foo['bar'] }}
n
It’s important to know that the outer double-curly braces {{ ... }} are not part of the variable itself, but are the print statement that tells Jinja to output the result. If you access variables inside tags (like an if statement or a for loop), don’t put the braces around them.
nn
{% if user.is_active %}n Welcome, {{ user.name }}!n{% endif %}
n
nn
Handling Undefined Values
n
If a variable or an attribute does not exist in the context, Jinja will return an undefined value. The behavior of this undefined value depends on the application’s configuration. By default, if you try to print an undefined value, it will evaluate to an empty string. However, if you try to perform any other operation on it (such as a mathematical calculation), it will raise an error and cause the template rendering to fail. This is a crucial safety mechanism that prevents silent failures and helps you to debug issues in your templates.
nn
n
n
