Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 72 ยท Templates with Jinja

Jinja Templates Basics

Learn the basics of Jinja templates in Flask: render_template, passing variables, expressions, filters, automatic HTML escaping and how Flask finds template files.

Until now our views returned short strings. Real pages are much bigger: a header, a navigation bar, a list of articles, a footer. Building that HTML with Python string concatenation is slow to write and dangerous, because every piece of user data you forget to escape becomes a security hole.

Flask ships with Jinja, a template engine. A template is an HTML file with placeholders. You hand Jinja the data, and it fills in the placeholders and returns finished HTML. Jinja escapes values for you, so a username like <script> shows up as text instead of running. In this lesson you'll render templates, print variables and expressions, apply filters, and see how autoescaping protects your pages.

From data to HTML

flowchart LR
    V["view: render_template('hello.html', name='Ada')"] --> E["Jinja environment"]
    T["template file<br/>hello.html"] --> E
    E --> H["finished HTML string"]
    H --> R["Response (200, text/html)"]

The view supplies the data, the template supplies the layout, Jinja combines them.

render_template(name, **context) loads the template called name, renders it with the keyword arguments as variables, and returns a string. Returning that string from the view sends the page. Flask looks for template files in a folder named templates next to your application code. We can't create files in the browser, so the examples use render_template_string, which takes the template text directly. Everything below works the same for files.

Three kinds of delimiters

Jinja only looks at text inside special markers:

Syntax Purpose Example
{{ ... }} Expression: print a value {{ user.name }}
{% ... %} Statement: loops, conditions, blocks {% if admin %}
{# ... #} Comment: not sent to the browser {# todo #}

Everything else is copied to the output as it is.

Python Variables, attributes 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.

Points worth noticing:

  • profile["email"] and profile.city both work for dictionaries. Jinja's dot syntax tries an attribute first and an item second, so profile.city finds the dictionary key. If a key collides with a dict method (profile.items), use the subscript form profile["items"].
  • You can call methods: author.shout().
  • Expressions can use arithmetic, comparison, the string-join operator ~, and the inline conditional a if cond else b.
  • A variable that does not exist prints as nothing, silently. That is friendly but can hide typos. Jinja's StrictUndefined option makes it an error instead; see Filters, Tests and Custom Helpers.

Filters

A filter transforms a value. You apply it with the pipe symbol and chain as many as you like: {{ title | trim | title }}. Some filters take arguments in parentheses: {{ items | join(", ") }}.

A handful you'll use daily: upper, lower, title, capitalize, length, default, join, round, truncate, striptags, safe, tojson. The default filter deserves a special mention, because it gives a fallback for missing or empty values:

HTML
<p>Nickname: {{ nickname | default("anonymous") }}</p>
<p>Bio: {{ bio | default("No bio yet.", true) }}</p>

The second argument true makes default also replace empty or false-like values (an empty string, 0, None), not just undefined ones. Filters, Tests and Custom Helpers covers the whole list and shows how to write your own.

Autoescaping: the safety net

HTML treats <, >, & and quotes as syntax. If a user chooses the name <script>alert(1)</script> and you paste it into HTML, their script will run in every visitor's browser. That attack is called cross-site scripting (XSS).

Flask turns autoescaping on for templates ending in .html, .htm, .xml, .xhtml and .svg, and for strings passed to render_template_string. Jinja then converts the dangerous characters into entities (&lt;) in every {{ ... }} output.

Python Autoescape on, off and safe

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.

Case 2 is the reason to prefer Flask's own rendering functions over creating jinja2.Template objects yourself: the escaping default differs. Cases 3 and 4 show the two ways out. The safe filter and the Markup class both promise Jinja that a string already is valid, trustworthy HTML.

Never apply | safe to text that came from a user, a database field filled by users, or a URL. Reserve it for HTML that your own code generated, and escape any user data inside it first. Web Security Essentials goes deeper.

Template files and the DictLoader stand-in

In a project, templates live in files:

TEXT
myapp/
  app.py
  templates/
    index.html
    articles/
      detail.html

and the view calls render_template("articles/detail.html", article=article). The name is a path relative to the templates folder, with forward slashes.

Jinja finds files through a loader. Flask's default loader reads the templates folder. We can imitate a template folder in memory by giving the app a DictLoader, a Jinja loader that serves templates from a dictionary. Everything else (including render_template) behaves exactly as with files:

Python render_template with an in-memory template folder

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.

In the output, the & in "Small & useful" and the angle brackets in the author name were escaped, because the template name ends in .html. If Flask can't find a name you ask for, it raises TemplateNotFound, a very common beginner error: check the spelling, the folder name templates (plural), and that the folder is next to the module that creates the Flask object.

Passing data to templates

Pass anything as keyword arguments: strings, numbers, lists, dicts, class instances, even functions. Some names are always available in every template without passing them: request, session, g and config (the app's configuration), plus the functions url_for and get_flashed_messages. For example, <a href="{{ url_for('home') }}">Home</a> builds a link as in Building URLs with url_for.

Keep logic out of templates: compute values in the view and pass finished data. Templates should mostly print and loop; the next lesson shows the loops and conditions that belong there.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which delimiter prints the value of a variable?

    Double braces output an expression. Percent-braces are statements, and hash-braces are comments.
  2. 2. A user's display name is <b>Eve</b>. What does {{ name }} output in a Flask .html template?

    Autoescaping converts HTML special characters into entities, which prevents XSS.
  3. 3. When is the | safe filter appropriate?

    safe disables escaping for that value, so it must never be applied to untrusted data.
  4. 4. What does a template print for {{ missing }} when no variable missing was passed (default settings)?

    Undefined variables render as empty output by default; StrictUndefined would raise an error instead.
  5. 5. Where does Flask's default loader look for render_template('index.html')?

    The default template folder is named templates and sits beside the module (or package) that creates the Flask object.

Summary

  • Jinja templates mix HTML with {{ expressions }}, {% statements %} and {# comments #}.
  • render_template("page.html", **data) renders a file from the templates folder; render_template_string renders text directly.
  • Attribute and item lookup both work with the dot; method calls, arithmetic and inline conditionals are allowed in expressions.
  • Filters (| upper, | default("x"), | length) transform values and can be chained.
  • Autoescaping is on in Flask for HTML-like templates and protects against XSS; use | safe or Markup only for trusted HTML.
  • A DictLoader is a convenient way to try templates without files.

Next: Loops and Conditionals in Templates, repeating and choosing markup.