Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 72 ยท Templates with Jinja

Filters, Tests and Custom Helpers

Format data in Jinja with built-in filters and tests, then write your own with template_filter, template_test, context processors and template globals in Flask.

Data rarely arrives in the shape you want to show. A price is a float like 1234.5 but the page should say $1,234.50. A name arrives in lower case. A list may be empty and needs a friendly message. Doing this cleanup in your view functions mixes presentation into logic. Jinja gives you better tools: filters transform a value, tests ask a yes-or-no question about it, and Flask lets you add your own filters and shared variables so every template can use them.

In this lesson you will use the most helpful built-in filters, write custom filters and tests, and use context processors and template globals to make data and helper functions available everywhere. The examples use in-memory templates through render_template_string; see Jinja template basics if that is new.

Filters: transform a value with a pipe

A filter is applied with the pipe character: {{ name|upper }}. Filters can take arguments in parentheses and can be chained, left to right.

Python Common built-in filters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two details trip people up. First, default only replaces values that are undefined (a variable that was never passed), so nickname falls back to anonymous. A value that exists but is None or empty is kept, unless you write default("x", true), which also replaces anything false-like. Second, filters apply to the expression on their left, so {{ 3 + 4|string }} applies string to 4 first; add parentheses when in doubt: {{ (3 + 4)|string }}.

Filters that deal with HTML safety

Flask turns on autoescaping for .html templates: a value containing <script> is printed as harmless text. Three filters let you control this:

  • escape (or e) escapes a value explicitly. Useful in strings built by format or replace.
  • safe marks a value as already safe so it is not escaped. Use it only for HTML that you wrote yourself, never for user input.
  • striptags removes tags and collapses whitespace, handy for a plain-text preview.
Python escape, safe and striptags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second line shows why safe is dangerous: the script tag goes straight into the page. Prefer building trusted HTML with markupsafe.Markup, as the last line does, because the intent is visible in Python. Web security essentials returns to this.

Tests: yes-or-no questions

A test is used with the word is: {% if count is odd %}. Tests return True or False and make conditions read like English. Some useful ones are defined, undefined, none, string, number, sequence, mapping, iterable, even, odd, divisibleby(n), lower, upper and in(seq). The test is not flips the answer.

Python Built-in tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A common real-world use is {% if user.bio is not none %}, which separates "no bio yet" (None) from "an empty bio". For a plain truth check you can still write {% if user.bio %}.

Your own filters

When the built-ins are not enough, write a plain Python function whose first argument is the value being filtered, and register it with the @app.template_filter() decorator. The function name becomes the filter name unless you pass one.

Python Currency and relative-size filters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice the registration details. @app.template_filter() with no argument uses the function name (money); @app.template_filter("filesize") registers human_size under another name. The registrations land in app.jinja_env.filters, a plain dictionary, so you can also add one directly: app.jinja_env.filters["money"] = money.

If a filter returns HTML, wrap the result in Markup and escape any user-supplied parts with markupsafe.escape, otherwise autoescape will print your tags as text. A filter that returns plain text is escaped automatically, which is what you want.

Custom tests

Tests have their own decorator, @app.template_test(). The function receives the value (and optional extra arguments) and returns a bool:

Python
@app.template_test("adult")
def is_adult(user):
    return user["age"] >= 18

In a template that reads {% if user is adult %}. Write a test when the condition has a name in your domain; it keeps business rules out of the template logic.

Context processors: variables for every template

Sometimes every page needs the same data, such as the site name, the current year or the logged-in user. Passing it from every view would be repetitive. A context processor is a function that returns a dictionary; Flask merges that dictionary into the variables of every template it renders.

Python Context processors and template globals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Neither view passed site_name or year; the context processor supplied them. The same file shows two ways to add globals. @app.template_global() registers a function callable from any template (initials(...)), and app.jinja_env.globals[...] adds any value, here a constant string. Both are visible in every template without importing.

flowchart LR
    V["View function<br/>render_template(name, **vars)"] --> M["Merge variables"]
    CP["Context processors"] --> M
    G["jinja_env.globals<br/>and template_global"] --> M
    F["Flask defaults:<br/>request, session, g, config, url_for"] --> M
    M --> T["Template renders"]

Template variables come from four places: your view, context processors, globals, and Flask's own defaults.

A few guidelines for these hooks:

  • Keep context processors cheap. They run on every render. A database query inside one runs for every page, so cache or load lazily.
  • Variables you pass explicitly win over context-processor values with the same name, so a view can still override a default.
  • Prefer a global function over a global value when the answer depends on arguments, such as initials(name).
  • Do not hide business logic in templates. If a helper has more than a few lines or needs testing, keep it as a normal Python function in a module and register it.

Summary of where the helpers live

Need Tool Registration
Reshape one value filter @app.template_filter()
Ask a yes/no question test @app.template_test()
Call a function from a template global @app.template_global()
Share data with every template context processor @app.context_processor

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does {{ name|trim|upper }} do?

    Filters are applied left to right, each one receiving the result of the previous one.
  2. 2. Which decorator makes a function available as a template test, used like {% if user is adult %}?

    Filters transform values with a pipe, tests answer questions after 'is', and globals are plain functions callable in templates.
  3. 3. A context processor returns {"year": 2030}. What is the effect?

    Flask merges the dictionary into the context of every render. Variables passed directly from a view take precedence over it.
  4. 4. When is it appropriate to use the safe filter?

    safe turns off autoescaping for that value. With user-supplied text it opens the door to cross-site scripting.
  5. 5. What does {{ nickname|default("anonymous") }} print when nickname exists but equals an empty string?

    Without the second argument true, default only reacts to undefined values. Use default("anonymous", true) to also replace empty or false-like values.

Summary

  • Filters (value|name(args)) transform values and chain left to right; tests (value is name) return booleans.
  • Useful built-ins include default, length, join, sort, round, truncate, escape, safe and striptags.
  • Register your own with @app.template_filter() and @app.template_test(); they live in app.jinja_env.filters and app.jinja_env.tests.
  • @app.context_processor injects variables into every template; @app.template_global() and jinja_env.globals add functions and constants.
  • Autoescape protects you by default; use safe or Markup only for HTML you control.

Next: serve CSS, JavaScript and images in static files and assets.