Navigation

Template Designer Documentation¶

This document describes the syntax and semantics of the template engine and will be most useful as reference to those creating Jinja templates. As the template engine is very flexible the configuration from the application might be slightly different from here in terms of delimiters and behavior of undefined values.

Synopsis¶

A template is simply a text file. It can generate any text-based format (HTML, XML, CSV, LaTeX, etc.). It doesn’t have a specific extension, .html or .xml are just fine.

A template contains variables or expressions, which get replaced with values when the template is evaluated, and tags, which control the logic of the template. The template syntax is heavily inspired by Django and Python.

Below is a minimal template that illustrates a few basics. We will cover the details later in that document:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title>My Webpage</title>
</head>
<body>
    <ul id="navigation">
    {% for item in navigation %}
        <li><a class="{{ item.href }}">{{ item.caption }}</a></li>
    {% endfor %}
    </ul>

    <h1>My Webpage</h1>
    {{ a_variable }}
</body>
</html>

This covers the default settings. The application developer might have changed the syntax from {% foo %} to <% foo %> or something similar.

There are two kinds of delimiters. {% ... %} and {{ ... }}. The first one is used to execute statements such as for-loops or assign values, the latter prints the result of the expression to the template.

Variables¶

The application passes variables to the templates you can mess around in the template. Variables may have attributes or elements on them you can access too. How a variable looks like, heavily depends on the application providing those.

You can use a dot (.) to access attributes of a variable, alternative the so-called “subscript” syntax ([]) can be used. The following lines do the same:

{{ foo.bar }}
{{ foo['bar'] }}

It’s important to know that the curly braces are not part of the variable but the print statement. If you access variables inside tags don’t put the braces around.

If a variable or attribute does not exist you will get back an undefined value. What you can do with that kind of value depends on the application configuration, the default behavior is that it evaluates to an empty string if printed and that you can iterate over it, but every other operation fails.

Implementation

For convenience sake foo.bar in Jinja2 does the following things on the Python layer:

  • check if there is an attribute called bar on foo.
  • if there is not, check if there is an item 'bar' in foo.
  • if there is not, return an undefined object.

foo['bar'] on the other hand works mostly the same with the a small difference in the order:

  • check if there is an item 'bar' in foo.
  • if there is not, check if there is an attribute called bar on foo.
  • if there is not, return an undefined object.

This is important if an object has an item or attribute with the same name. Additionally there is the attr() filter that just looks up attributes.

Filters¶

Variables can be modified by filters. Filters are separated from the variable by a pipe symbol (|) and may have optional arguments in parentheses. Multiple filters can be chained. The output of one filter is applied to the next.

{{ name|striptags|title }} for example will remove all HTML Tags from the name and title-cases it. Filters that accept arguments have parentheses around the arguments, like a function call. This example will join a list by commas: {{ list|join(', ') }}.

The List of Builtin Filters below describes all the builtin filters.

Tests¶

Beside filters there are also so called “tests” available. Tests can be used to test a variable against a common expression. To test a variable or expression you add is plus the name of the test after the variable. For example to find out if a variable is defined you can do name is defined which will then return true or false depending on if name is defined.

Tests can accept arguments too. If the test only takes one argument you can leave out the parentheses to group them. For example the following two expressions do the same:

{% if loop.index is divisibleby 3 %}
{% if loop.index is divisibleby(3) %}

The List of Builtin Tests below describes all the builtin tests.

Comments¶

To comment-out part of a line in a template, use the comment syntax which is by default set to {# ... #}. This is useful to comment out parts of the template for debugging or to add information for other template designers or yourself:

{# note: disabled template because we no longer use this
    {% for user in users %}
        ...
    {% endfor %}
#}

Whitespace Control¶

In the default configuration whitespace is not further modified by the template engine, so each whitespace (spaces, tabs, newlines etc.) is returned unchanged. If the application configures Jinja to trim_blocks the first newline after a a template tag is removed automatically (like in PHP).

But you can also strip whitespace in templates by hand. If you put an minus sign (-) to the start or end of an block (for example a for tag), a comment or variable expression you can remove the whitespaces after or before that block:

{% for item in seq -%}
    {{ item }}
{%- endfor %}

This will yield all elements without whitespace between them. If seq was a list of numbers from 1 to 9 the output would be 123456789.

If Line Statements are enabled they strip leading whitespace automatically up to the beginning of the line.

Note

You must not use a whitespace between the tag and the minus sign.

valid:

{%- if foo -%}...{% endif %}

invalid:

{% - if foo - %}...{% endif %}

Escaping¶

It is sometimes desirable or even necessary to have Jinja ignore parts it would otherwise handle as variables or blocks. For example if the default syntax is used and you want to use {{ as raw string in the template and not start a variable you have to use a trick.

The easiest way is to output the variable delimiter ({{) by using a variable expression:

{{ '{{' }}

For bigger sections it makes sense to mark a block raw. For example to put Jinja syntax as example into a template you can use this snippet:

{% raw %}
    <ul>
    {% for item in seq %}
        <li>{{ item }}</li>
    {% endfor %}
    </ul>
{% endraw %}

Line Statements¶

If line statements are enabled by the application it’s possible to mark a line as a statement. For example if the line statement prefix is configured to # the following two examples are equivalent:

<ul>
# for item in seq
    <li>{{ item }}</li>
# endfor
</ul>

<ul>
{% for item in seq %}
    <li>{{ item }}</li>
{% endfor %}
</ul>

The line statement prefix can appear anywhere on the line as long as no text precedes it. For better readability statements that start a block (such as for, if, elif etc.) may end with a colon:

# for item in seq:
    ...
# endfor

Note

Line statements can span multiple lines if there are open parentheses, braces or brackets:

<ul>
# for href, caption in [('index.html', 'Index'),
                        ('about.html', 'About')]:
    <li><a class="{{ href }}">{{ caption }}</a></li>
# endfor
</ul>

Since Jinja 2.2 line-based comments are available as well. For example if the line-comment prefix is configured to be ## everything from ## to the end of the line is ignored (excluding the newline sign):

# for item in seq:
    <li>{{ item }}</li>     ## this comment is ignored
# endfor

Template Inheritance¶

The most powerful part of Jinja is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override.

Sounds complicated but is very basic. It’s easiest to understand it by starting with an example.

Base Template¶

This template, which we’ll call base.html, defines a simple HTML skeleton document that you might use for a simple two-column page. It’s the job of “child” templates to fill the empty blocks with content:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<html xmlns="www.w3.org/1999/xhtml">
<head>
    {% block head %}
    <link rel="stylesheet" class="style.css" />
    <title>{% block title %}{% endblock %} - My Webpage</title>
    {% endblock %}
</head>
<body>
    <div id="content">{% block content %}{% endblock %}</div>
    <div id="footer">
        {% block footer %}
        &copy; Copyright 2008 by <a class="domain.invalid/">you</a>.
        {% endblock %}
    </div>
</body>

In this example, the {% block %} tags define four blocks that child templates can fill in. All the block tag does is to tell the template engine that a child template may override those portions of the template.

Child Template¶

A child template might look like this:

{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
    {{ super() }}
    <style type="text/css">
        .important { color: #336699; }
    </style>
{% endblock %}
{% block content %}
    <h1>Index</h1>
    <p class="important">
      Welcome on my awesome homepage.
    </p>
{% endblock %}

The {% extends %} tag is the key here. It tells the template engine that this template “extends” another template. When the template system evaluates this template, first it locates the parent. The extends tag should be the first tag in the template. Everything before it is printed out normally and may cause confusion. For details about this behavior and how to take advantage of it, see Null-Master Fallback.

The filename of the template depends on the template loader. For example the FileSystemLoader allows you to access other templates by giving the filename. You can access templates in subdirectories with an slash:

{% extends "layout/default.html" %}

But this behavior can depend on the application embedding Jinja. Note that since the child template doesn’t define the footer block, the value from the parent template is used instead.

You can’t define multiple {% block %} tags with the same name in the same template. This limitation exists because a block tag works in “both” directions. That is, a block tag doesn’t just provide a hole to fill - it also defines the content that fills the hole in the parent. If there were two similarly-named {% block %} tags in a template, that template’s parent wouldn’t know which one of the blocks’ content to use.

If you want to print a block multiple times you can however use the special self variable and call the block with that name:

<title>{% block title %}{% endblock %}</title>
<h1>{{ self.title() }}</h1>
{% block body %}{% endblock %}

Super Blocks¶

It’s possible to render the contents of the parent block by calling super. This gives back the results of the parent block:

{% block sidebar %}
    <h3>Table Of Contents</h3>
    ...
    {{ super() }}
{% endblock %}

Named Block End-Tags¶

Jinja2 allows you to put the name of the block after the end tag for better readability:

{% block sidebar %}
    {% block inner_sidebar %}
        ...
    {% endblock inner_sidebar %}
{% endblock sidebar %}

However the name after the endblock word must match the block name.

Block Nesting and Scope¶

Blocks can be nested for more complex layouts. However per default blocks may not access variables from outer scopes:

{% for item in seq %}
    <li>{% block loop_item %}{{ item }}{% endblock %}</li>
{% endfor %}

This example would output empty <li> items because item is unavailable inside the block. The reason for this is that if the block is replaced by a child template a variable would appear that was not defined in the block or passed to the context.

Starting with Jinja 2.2 you can explicitly specify that variables are available in a block by setting the block to “scoped” by adding the scoped modifier to a block declaration:

{% for item in seq %}
    <li>{% block loop_item scoped %}{{ item }}{% endblock %}</li>
{% endfor %}

When overriding a block the scoped modifier does not have to be provided.

Template Objects¶

Changed in version 2.4.

If a template object was passed to the template context you can extend from that object as well. Assuming the calling code passes a layout template as layout_template to the environment, this code works:

{% extends layout_template %}

Previously the layout_template variable had to be a string with the layout template’s filename for this to work.

HTML Escaping¶

When generating HTML from templates, there’s always a risk that a variable will include characters that affect the resulting HTML. There are two approaches: manually escaping each variable or automatically escaping everything by default.

Jinja supports both, but what is used depends on the application configuration. The default configuaration is no automatic escaping for various reasons:

  • escaping everything except of safe values will also mean that Jinja is escaping variables known to not include HTML such as numbers which is a huge performance hit.
  • The information about the safety of a variable is very fragile. It could happen that by coercing safe and unsafe values the return value is double escaped HTML.

Working with Manual Escaping¶

If manual escaping is enabled it’s your responsibility to escape variables if needed. What to escape? If you have a variable that may include any of the following chars (>, <, &, or ") you have to escape it unless the variable contains well-formed and trusted HTML. Escaping works by piping the variable through the |e filter: {{ user.username|e }}.

Working with Automatic Escaping¶

When automatic escaping is enabled everything is escaped by default except for values explicitly marked as safe. Those can either be marked by the application or in the template by using the |safe filter. The main problem with this approach is that Python itself doesn’t have the concept of tainted values so the information if a value is safe or unsafe can get lost. If the information is lost escaping will take place which means that you could end up with double escaped contents.

Double escaping is easy to avoid however, just rely on the tools Jinja2 provides and don’t use builtin Python constructs such as the string modulo operator.

Functions returning template data (macros, super, self.BLOCKNAME) return safe markup always.

String literals in templates with automatic escaping are considered unsafe too. The reason for this is that the safe string is an extension to Python and not every library will work properly with it.

List of Control Structures¶

A control structure refers to all those things that control the flow of a program - conditionals (i.e. if/elif/else), for-loops, as well as things like macros and blocks. Control structures appear inside {% ... %} blocks in the default syntax.

For¶

Loop over each item in a sequence. For example, to display a list of users provided in a variable called users:

<h1>Members</h1>
<ul>
{% for user in users %}
  <li>{{ user.username|e }}</li>
{% endfor %}
</ul>

Inside of a for loop block you can access some special variables:

Variable Description
loop.index The current iteration of the loop. (1 indexed)
loop.index0 The current iteration of the loop. (0 indexed)
loop.revindex The number of iterations from the end of the loop (1 indexed)
loop.revindex0 The number of iterations from the end of the loop (0 indexed)
loop.first True if first iteration.
loop.last True if last iteration.
loop.length The number of items in the sequence.
loop.cycle A helper function to cycle between a list of sequences. See the explanation below.

Within a for-loop, it’s possible to cycle among a list of strings/variables each time through the loop by using the special loop.cycle helper:

{% for row in rows %}
    <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
{% endfor %}

With Jinja 2.1 an extra cycle helper exists that allows loop-unbound cycling. For more information have a look at the List of Global Functions.

Unlike in Python it’s not possible to break or continue in a loop. You can however filter the sequence during iteration which allows you to skip items. The following example skips all the users which are hidden:

{% for user in users if not user.hidden %}
    <li>{{ user.username|e }}</li>
{% endfor %}

The advantage is that the special loop variable will count correctly thus not counting the users not iterated over.

If no iteration took place because the sequence was empty or the filtering removed all the items from the sequence you can render a replacement block by using else:

<ul>
{% for user in users %}
    <li>{{ user.username|e }}</li>
{% else %}
    <li><em>no users found</em></li>
{% endfor %}
</ul>

It is also possible to use loops recursively. This is useful if you are dealing with recursive data such as sitemaps. To use loops recursively you basically have to add the recursive modifier to the loop definition and call the loop variable with the new iterable where you want to recurse.

The following example implements a sitemap with recursive loops:

<ul class="sitemap">
{%- for item in sitemap recursive %}
    <li><a class="{{ item.href|e }}">{{ item.title }}</a>
    {%- if item.children -%}
        <ul class="submenu">{{ loop(item.children) }}</ul>
    {%- endif %}</li>
{%- endfor %}
</ul>

If¶

The if statement in Jinja is comparable with the if statements of Python. In the simplest form you can use it to test if a variable is defined, not empty or not false:

{% if users %}
<ul>
{% for user in users %}
    <li>{{ user.username|e }}</li>
{% endfor %}
</ul>
{% endif %}

For multiple branches elif and else can be used like in Python. You can use more complex Expressions there too:

{% if kenny.sick %}
    Kenny is sick.
{% elif kenny.dead %}
    You killed Kenny!  You bastard!!!
{% else %}
    Kenny looks okay --- so far
{% endif %}

If can also be used as inline expression and for loop filtering.

Macros¶

Macros are comparable with functions in regular programming languages. They are useful to put often used idioms into reusable functions to not repeat yourself.

Here a small example of a macro that renders a form element:

{% macro input(name, value='', type='text', size=20) -%}
    <input type="{{ type }}" name="{{ name }}" value="{{
        value|e }}" size="{{ size }}">
{%- endmacro %}

The macro can then be called like a function in the namespace:

<p>{{ input('username') }}</p>
<p>{{ input('password', type='password') }}</p>

If the macro was defined in a different template you have to import it first.

Inside macros you have access to three special variables:

varargs
If more positional arguments are passed to the macro than accepted by the macro they end up in the special varargs variable as list of values.
kwargs
Like varargs but for keyword arguments. All unconsumed keyword arguments are stored in this special variable.
caller
If the macro was called from a call tag the caller is stored in this variable as macro which can be called.

Macros also expose some of their internal details. The following attributes are available on a macro object:

name
The name of the macro. {{ input.name }} will print input.
arguments
A tuple of the names of arguments the macro accepts.
defaults
A tuple of default values.
catch_kwargs
This is true if the macro accepts extra keyword arguments (ie: accesses the special kwargs variable).
catch_varargs
This is true if the macro accepts extra positional arguments (ie: accesses the special varargs variable).
caller
This is true if the macro accesses the special caller variable and may be called from a call tag.

If a macro name starts with an underscore it&

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.