Expressions are most of what templates contain, and their lookup rules explain many surprising blanks.
Inside {{ }} you write expressions, which look a lot like Python:
- attribute or key access:
user.nameanduser["name"]both work. The dot form tries the attribute first, then the item; the subscript form tries the item first. - literals: strings, numbers, lists
[1, 2], dicts{"a": 1},true/false(lowercase also works fornone) - math:
+ - * / // % ** - comparisons and logic:
== != < >= and or not in ~converts both sides to strings and concatenates:{{ "Item " ~ n }}- inline if:
{{ "yes" if ok else "no" }}; theelseis optional - calling methods:
{{ name.upper() }},{{ items|length }}(filters come next)
Assign with {% set total = price * qty %}.
Undefined values are not errors by default. A missing variable, or a missing attribute or key on an existing object, becomes an Undefined object that prints as an empty string, so a typo like {{ user.nmae }} silently renders nothing. Going one step further, accessing an attribute of an undefined value ({{ usr.name }} when usr itself is missing) raises UndefinedError. Later you'll see StrictUndefined, which makes every missing value an error and is a good choice in development and for config generation.
Templates are meant to display data, not compute it. Jinja can call any method you pass in, so keep heavy logic in Python and give templates ready-to-show values.
Example
from jinja2 import Template
t = Template("""{% set total = price * qty -%}
{{ user.name }} / {{ user["role"] }}
{{ "Order " ~ order_id }}: {{ qty }} x {{ price }} = {{ total }}
{{ "bulk" if qty >= 10 else "single" }}
{{ tags[0].upper() }} and {{ tags|length }} tags
[{{ user.nmae }}] typo renders empty""")
print(t.render(user={"name": "Ann", "role": "admin"}, order_id=7,
qty=12, price=2.5, tags=["new", "sale"]))
# Ann / admin
# Order 7: 12 x 2.5 = 30.0
# bulk
# NEW and 2 tags
# [] typo renders emptyRemember
- a.b tries attribute then key; a["b"] tries key then attribute
- ~ concatenates as strings; x if cond else y works inline
- Missing values render as empty strings unless you use StrictUndefined
Watch out for
- Debugging a blank output for minutes when it was a misspelled variable.