Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Jinja2 Templates: Variables, Loops, and Conditions

Learn how Jinja2 variables, for loops, and if conditions work in Python templates, including filters, undefined-variable handling, whitespace control, and performance tips.

~5 min readPython
#Jinja2#Python#Templating#Variables
Illustration of a Jinja2 template with variables, loops, and conditions generating dynamic output.

Jinja2 is a Python templating engine for generating dynamic text, HTML, or configuration files. Its core building blocks—variables, loops, and conditions—let you transform data into output without embedding complex logic in your application code. This guide explains the syntax and runtime behavior of each construct, with examples and the edge cases that often trip up developers.

Variables in Jinja2 Templates

Variables are rendered with double curly braces: {{ variable }}. The variable name can reference a top-level variable in the context passed to the template, or a nested attribute or dictionary key using dot notation or subscript syntax.

python
from jinja2 import Template template = Template("Hello, {{ name }}! You have {{ messages | length }} new messages.") print(template.render(name="Alice", messages=["a", "b"]))

Here, name and messages are provided via render(). Filters, like length, modify the variable's output. Common filters include default, upper, lower, join, and int. Filters can also be chained: {{ value | default('none') | upper }}.

When accessing dictionary keys, both {{ user['name'] }} and {{ user.name }} work. The dot syntax is often preferred for readability, but it fails if the key contains characters that are not valid identifiers. In that case, use the bracket syntax.

Looping with for and Loop Variables

The for loop iterates over any iterable, including lists, tuples, dictionaries, and generator objects. The basic syntax is:

jinja
{% for item in items %} {{ item }} {% endfor %}

Jinja2 provides a special loop variable inside every loop, exposing useful metadata:

Loop VariableDescription
loop.indexThe current iteration number (1-based)
loop.index0The current iteration number (0-based)
loop.firstTrue if this is the first iteration
loop.lastTrue if this is the last iteration
loop.lengthTotal number of items
loop.previtemThe previous item, if any
loop.nextitemThe next item, if any

These are invaluable for formatting comma-separated lists or adding CSS classes to alternating rows.

jinja
<ul> {% for user in users %} <li class="{{ 'even' if loop.index is even else 'odd' }}">{{ user.name }}</li> {% endfor %} </ul>

If the iterable is empty, you can provide an {% else %} block that renders instead:

jinja
{% for item in items %} {{ item }} {% else %} No items found. {% endfor %}

Iterating over a dictionary yields its keys by default. To get key-value pairs, call .items():

jinja
{% for key, value in config.items() %} {{ key }}: {{ value }} {% endfor %}

Conditions with if, elif, and else

Conditional blocks use {% if %}, {% elif %}, and {% else %}. The condition can be any expression that evaluates to a truthy or falsy value, including comparisons, boolean operators, and tests.

jinja
{% if user.is_admin %} <p>Admin panel</p> {% elif user.is_moderator %} <p>Moderator view</p> {% else %} <p>Regular user</p> {% endif %}

Jinja2 supports standard comparison operators (==, !=, <, >, <=, >=) and logical operators (and, or, not). Parentheses can be used to group conditions.

Tests are special functions that return a boolean. Common tests include defined, undefined, none, string, number, and mapping. For example, to check whether a variable exists before using it:

jinja
{% if user is defined %} Hello, {{ user.name }} {% endif %}

You can also use inline conditional expressions, similar to a ternary operator:

jinja
{{ 'yes' if flag else 'no' }}

This is useful for setting class names or other short values.

Combining Loops and Conditions

Loops and conditions often appear together. The most common pattern is to filter items inside a loop using an if statement:

jinja
{% for item in items %} {% if item.visible %} {{ item.name }} {% endif %} {% endfor %}

However, Jinja2 does not support break or continue in loops. To skip items based on a condition, you can use an if clause in the loop expression, pre-process the data in Python before rendering, or use filters such as selectattr to iterate over a filtered sequence.

jinja
{% for item in items if item.visible %} {{ item.name }} {% endfor %}

The if clause directly after the for expression filters the iterable. This is more concise and often more readable than a nested conditional.

For attribute-based filtering, Jinja2 provides the selectattr filter:

jinja
{% for item in items | selectattr('visible') %} {{ item.name }} {% endfor %}

selectattr keeps objects whose named attribute is truthy. This approach avoids cluttering the template with nested conditionals and keeps the logic declarative.

Handling Undefined Variables and Filters

By default, an undefined variable renders as an empty string. This can mask bugs, especially when a variable name is misspelled. To control this behavior, use the default filter:

jinja
{{ missing | default('fallback') }}

You can also use the defined test in conditions:

jinja
{% if missing is defined %} {{ missing }} {% else %} <p>Value not provided</p> {% endif %}

Jinja2's Undefined class can be customized at environment creation to raise exceptions on undefined variables, which is helpful during development. For example, Environment(undefined=StrictUndefined) will raise an UndefinedError instead of silently rendering nothing.

Filters themselves can also fail when the input type is unexpected. For instance, calling length on a value that does not support len() raises an error. Ensure the variable is the expected type, or check it with a test first.

Whitespace Control and Output Formatting

Jinja2 preserves whitespace in templates by default, which can lead to unwanted blank lines in rendered output. To control this, you can trim whitespace around block tags using a hyphen: {%- and -%}.

jinja
<ul> {%- for item in items %} <li>{{ item }}</li> {%- endfor %} </ul>

The hyphen removes all whitespace (including newlines) before or after the tag. This is useful when generating HTML where indentation is not important.

Alternatively, you can configure the environment with trim_blocks=True and lstrip_blocks=True to automatically remove newlines after blocks and strip leading whitespace from lines containing block tags. This is often set globally in Flask or other frameworks.

python
from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader('templates'), trim_blocks=True, lstrip_blocks=True)

Be aware that aggressive whitespace trimming can make templates harder to read. Use it consistently and test the output to avoid unexpected formatting.

Performance and Maintainability Considerations

Templates should focus on presentation, not business logic. Complex loops and conditionals can make templates difficult to maintain and debug. When you find yourself writing deeply nested logic, consider moving the computation to Python and passing preprocessed data to the template.

Loops can become a performance bottleneck if they call expensive functions or access slow attributes repeatedly. For example, {{ item.get_expensive_data() }} inside a loop executes that method for every iteration. Cache such results in the context before rendering.

Jinja2 compiles templates to Python bytecode, so rendering is generally fast. Recompiling templates on every request is wasteful. Reuse a single Environment in production so Jinja2's template cache can store compiled templates. In Flask, TEMPLATES_AUTO_RELOAD only controls whether changed templates are reloaded during development; it is not a production caching toggle.

Finally, use macros to reuse repetitive markup. A macro is like a function defined in the template:

jinja
{% macro render_item(item) %} <li>{{ item.name }} - {{ item.price }}</li> {% endmacro %} <ul> {% for item in items %} {{ render_item(item) }} {% endfor %} </ul>

Macros reduce duplication and keep templates consistent, but avoid overusing them for trivial snippets where a simple loop would suffice.

By understanding how variables, loops, and conditions behave in Jinja2, you can write templates that are both expressive and efficient. The key is to keep template logic simple, use filters and tests to handle edge cases, and precompute data when loops would otherwise repeat expensive work.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.