Filters and tests

Jinja · Essentials · 12 min

Filters are how templates format data without Python code, and tests make conditions readable.

A filter transforms a value with the pipe syntax: {{ name|title }}. Filters chain left to right and can take arguments: {{ items|sort(attribute="price")|join(", ") }}.

Built-in filters you will use constantly:

  • text: upper, lower, title, capitalize, trim, truncate(30), replace("a", "b"), wordwrap, striptags
  • fallback: default("n/a") (alias d); default(x, true) also replaces empty or falsy values
  • collections: length, first, last, join, sort, unique, reverse, sum(attribute="price"), batch(3), groupby("category"), dictsort, items
  • functional style: map(attribute="name"), selectattr("active"), rejectattr("draft"), select("odd")
  • numbers and output: round(2), int, float, filesizeformat, format, tojson, e, safe

map, select and friends return generators; finish with join, list or first.

A test checks a value with is: {% if user is defined %}, {% if n is divisibleby(3) %}, {% if x is none %}, is string, is number, is even, is iterable, is sameas(false). Negate with is not. Tests also power select("odd") and selectattr("age", "ge", 18).

Filters and tests are applied before most operators, so {{ -3|abs }} is -(3|abs); use parentheses: {{ (-3)|abs }}.

Example

from jinja2 import Environment

env = Environment()
t = env.from_string("""{{ title|default("Untitled")|upper }}
{{ products|selectattr("in_stock")|map(attribute="name")|join(", ") }}
Total: {{ products|sum(attribute="price")|round(2) }}
{% for g in products|groupby("cat") %}{{ g.grouper }}={{ g.list|length }} {% endfor %}
{% for n in range(1, 7) if n is divisibleby(3) %}{{ n }} {% endfor %}
{{ bio|default("-", true) }} {{ note is defined }}""")

print(t.render(bio="", products=[
    {"name": "Pen", "price": 1.25, "cat": "office", "in_stock": True},
    {"name": "Ink", "price": 4.5, "cat": "office", "in_stock": False},
    {"name": "Mug", "price": 7.333, "cat": "kitchen", "in_stock": True}]))
# UNTITLED
# Pen, Mug
# Total: 13.08
# kitchen=1 office=2
# 3 6
# - False

Remember

  • value|filter(args) transforms; filters chain left to right
  • default, join, sort, map, selectattr and groupby cover most formatting
  • Tests use is: is defined, is none, is divisibleby(n)

Watch out for

  • Forgetting that map/select return generators; finish with join, list or first.

Check yourself

  1. What does {{ ""|default("none") }} render?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: jinja.palletsprojects.com/en/stable/templates/#list-of-builtin-filters