Skip to content
Tutorials Center
My learning

Topics

Lesson 107 of 149 ยท Data and the Web

Templates with Jinja2

Learn Jinja2 in plain Python. Render variables, filters, loops, macros and template inheritance, escape user input safely, add custom filters and see how Flask uses it.

Sooner or later a program has to produce text that mixes fixed wording with changing data: an HTML page, an email, a report, a configuration file. You could build the text with f-strings and concatenation, but that gets ugly fast. Loops, conditions and repeated layout end up tangled with your program logic, and one forgotten escape turns user input into a security hole.

A template engine separates the two jobs. You write the shape of the output once, in a template, with placeholders and a little logic. Your Python code supplies the data. Jinja2 is the most widely used template engine in Python. Flask uses it for every page, Ansible uses it for configuration files, and Django's template language borrows many of its ideas. Because Jinja2 is an ordinary library, you can use it on its own for any kind of text, and that is how this lesson teaches it.

If you have already read about templates in Web Development with Flask and Django, this lesson goes deeper into the engine itself. The Flask-specific details are covered in the Flask tutorial.

Rendering your first template

A template is a string (usually kept in a file) containing three kinds of markup:

Syntax Purpose
{{ expression }} Print the value of an expression
{% statement %} Run a statement such as if, for or block
{# comment #} A comment that never appears in the output

You create a Template, then call render() with keyword arguments. Each keyword becomes a variable inside the template.

The editors here run Python in your browser, so the example installs nothing special: Jinja2 is bundled with the in-browser Python. On your own machine you would run pip install jinja2 once (see Packages and pip).

Python Variables and expressions

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.

Inside {{ ... }} you can use dotted access, indexing, method calls and arithmetic. Jinja2 deliberately has a gentler lookup rule than Python: user.name first tries the attribute name and, if that doesn't exist, the dictionary key "name". That means the same template works whether you pass an object or a dictionary.

Filters

A filter transforms a value. You apply one with the pipe character, and you can chain several. They read left to right, like a Unix pipeline.

Python Chaining 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.

A few filters you will use constantly: default for missing values, join, length, round, truncate, sort, and the pair map / selectattr, which transform and filter whole lists. The full list is in the Jinja2 documentation, and later in this lesson you will write a filter of your own.

Loops and conditions

Statements use {% ... %} and every block needs an explicit end tag, because indentation means nothing to Jinja2. Inside a for loop you get a special loop variable with the position, and the loop can have an else branch that runs when the sequence is empty.

Python for, if and the loop variable

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 minus signs in {%- and -%}. They strip the whitespace (including newlines) next to the tag, which is how you keep the output tidy even though the template has to be indented to be readable. If your output has stray blank lines, whitespace control is the cure. Passing trim_blocks=True and lstrip_blocks=True to an Environment (next section) applies sensible defaults to every template at once.

The Environment: loaders, escaping and strict mode

Template("...") is fine for quick jobs. Real projects use an Environment, the object that holds your settings and finds your templates. It decides where templates come from (a folder, a package, a dictionary), whether output is escaped, and what happens when a variable is missing.

Two settings matter more than the rest:

  • autoescape. When on, Jinja2 replaces <, >, & and quotes in every printed value with HTML entities, so user text cannot inject markup. This is your main defense against cross-site scripting (see Python Security). Always turn it on for HTML. Flask does so for .html files automatically, but a bare Environment does not.
  • undefined=StrictUndefined. By default, a misspelled variable silently renders as an empty string, which hides bugs. StrictUndefined raises an error instead.
Python Autoescape and StrictUndefined

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 Markup class (from the markupsafe package that Jinja2 uses) marks a string as safe HTML, and the safe filter does the same for a single value. Use them only for text you produced. Never mark user input as safe.

Macros and includes: reusable pieces

A macro is a function written in the template language. Define it once and call it wherever you need the same snippet, such as a form field or a product card.

Python A macro for repeated markup

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.

Macros take positional and keyword arguments with defaults, just like Python functions. Notice that the double quotes in the name were escaped to &#34;, so they cannot break out of the value attribute. Larger projects keep macros in their own file and load them with {% from "forms.html" import field %}. A related tag, {% include "footer.html" %}, simply pastes another template in place.

Template inheritance

Every page of a website shares the same frame (header, navigation, footer) and differs only in the middle. Inheritance captures that. A base template defines named blocks; child templates say {% extends "base.html" %} and fill in only the blocks they want to change.

Templates normally live in files, found by a FileSystemLoader("templates"). In the browser there is no template folder, so this example uses a DictLoader, which looks templates up by name in a dictionary. Everything else is identical to loading from disk.

Python Base template and child pages

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.

{{ super() }} pulls in the parent's version of a block, so a child can add to it instead of replacing it. env.globals holds values and functions visible to every template, which is handy for things like the current year or a site name.

Writing your own filters

When the built-in filters are not enough, register a Python function as a filter. Its first argument is the value on the left of the pipe, and any further arguments come from the template.

Python A custom filter and a custom test

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.

Tests are the cousins of filters: is even, is defined, is none and so on return true or false for use in conditions. Registering your own keeps formatting rules in one Python function instead of copied across templates.

Jinja2 inside Flask

You have already been using everything above if you have built a Flask app. render_template("home.html", user="Ada") is a thin wrapper around env.get_template("home.html").render(user="Ada"). Flask creates the Environment for you, points the loader at the templates folder, switches autoescape on for HTML files, and adds helpers such as url_for and request to the globals. In Flask, a custom filter is registered with @app.template_filter() instead of env.filters[...].

Because the engine is the same, everything in this lesson (inheritance, macros, filters, whitespace control) works unchanged in your web pages. Outside the web, the same tools generate emails, Markdown reports, SQL scripts and config files.

Common mistakes

  • Forgetting autoescape=True when you use a bare Environment for HTML. Make it a habit, or use Flask's defaults.
  • Putting business logic in templates. Templates should format data, not decide things. Compute in Python, then pass the result in.
  • Stray blank lines and indentation in output. Reach for - whitespace control or trim_blocks and lstrip_blocks.
  • Trusting |safe on user-provided text. It removes the protection you turned on.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you print the value of a variable named price in a Jinja2 template?

    Double curly braces print an expression. {% %} is for statements such as if and for, and {# #} marks a comment that is never rendered.
  2. 2. What is the main purpose of autoescape=True on an Environment?

    Autoescaping is the main defense against cross-site scripting. A plain Environment has it off, so you must enable it yourself for HTML output.
  3. 3. A child template starts with {% extends "base.html" %}. Which statement is true?

    Inheritance lets a child replace named blocks while the rest of the page comes from the parent. {{ super() }} includes the parent's version of a block.
  4. 4. What does Environment(undefined=StrictUndefined) change?

    By default an undefined variable silently renders as empty text, which hides typos. StrictUndefined makes the mistake visible immediately.

Summary

  • A template engine keeps layout in templates and data in Python. Jinja2 uses {{ }} to print, {% %} for statements and {# #} for comments.
  • Filters ({{ x | upper }}) transform values and chain left to right; tests (x is even) give true or false.
  • for, if, and the loop variable do the logic. Use - inside tags (or trim_blocks) to control whitespace.
  • An Environment holds loaders and settings. Turn on autoescape for HTML and consider StrictUndefined to catch typos.
  • Macros are reusable template functions; inheritance (extends and block) builds many pages from one base layout.
  • Flask's render_template is Jinja2 with sensible defaults already configured.

Next: Flask-RESTful Resources, where you'll build REST endpoints out of resource classes.