Skip to content
Filters
step 1/5

Reading — step 1 of 5

Read

~1 min readVariables & Filters

Filters

Filters transform values:

{{ name | upper }}                  # "alice" → "ALICE"
{{ price | round(2) }}              # 3.14159 → 3.14
{{ items | length }}                # [1,2,3] → 3
{{ name | default("guest") }}       # missing → "guest"
{{ html | safe }}                   # don't escape
{{ text | truncate(50) }}
{{ items | join(", ") }}
{{ name | upper | reverse }}        # chained

Each filter is a function: f(value, *args) -> new_value.

python

Filter chain: value | f1 | f2 | f3f3(f2(f1(value))).

Auto-escaping:

  • HTML output: <, >, &, ", ' escaped to &lt;, etc.
  • Prevents XSS attacks if user content contains script tags.
  • | safe filter marks content as already-safe; bypass escape.
{{ user_input }}            -> &lt;script&gt;alert(1)&lt;/script&gt;   (escaped)
{{ user_input | safe }}      -> <script>alert(1)</script>             (DANGEROUS)
python

Custom filters: register in environment. Common in Jinja2 — env.filters['custom'] = my_func.

Globals + filters together: powerful but adds template complexity. Consider whether logic should be in templates vs in code.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…