ZetCode

Python Jinja

last modified October 30, 2026 Python 3.15

In this article we show how to create templates in Python with the Jinja module.

Python Jinja module

Jinja is a fast, expressive template engine for Python. Its syntax is similar to the Django template language; it is the template engine of the Flask framework and is also used by tools such as Ansible.

A template engine or template processor is a library designed to combine templates with a data model to produce documents. Template engines are often used to generate large amounts of emails, in source code preprocessing, to create configuration files, or to produce dynamic HTML pages.

A template contains static parts and dynamic parts. The dynamic parts are placeholders and statements that are later replaced with data. The rendering function combines the template with the data and produces the final text. Jinja compiles templates to Python bytecode, so rendering a loaded template is fast.

Do not confuse Jinja's Template class with string.templatelib.Template, the type of the template strings (t-strings) added in Python 3.14. A t-string is a language feature that gives you the literal parts and the interpolated values of a single expression; Jinja is a full template language with its own syntax, files, loops, and inheritance.

Jinja installation

The package is published on PyPI as Jinja2; the module is imported as jinja2. The examples were tested with Jinja 3.1.6 and Python 3.15. The MarkupSafe library, which implements HTML escaping, is installed as a dependency. The Flask example at the end also needs the flask package.

$ pip install jinja2 flask

Jinja delimiters

Jinja uses various delimiters in the template strings.

Jinja can also be configured to recognize line statements and line comments, for instance lines starting with # and ##. These are off by default; they are enabled with the line_statement_prefix and line_comment_prefix options of the Environment. The delimiters themselves can be changed as well, for instance when the output is a LaTeX document that uses curly brackets heavily.

Jinja simple example

In the first example, we create a very simple template.

simple.py
import sys

from jinja2 import Template

name = sys.argv[1] if len(sys.argv) > 1 else 'guest'

tm = Template('Hello {{ name }}')
msg = tm.render(name=name)

print(msg)

The example takes a user name from the command line and generates a message, which is printed to the console. If no name is given, it uses guest.

from jinja2 import Template

We import the Template class from the jinja2 module. Template represents a compiled template and is used to evaluate it.

tm = Template('Hello {{ name }}')

In our template, we have the {{ }} syntax which is used to print the variable. The variable is passed to the render method.

msg = tm.render(name=name)

With the render method, we generate the final output. The method joins the template string with the data passed as arguments. The variables that are passed to the render method form the template context.

$ python simple.py
Hello guest
$ python simple.py Paul
Hello Paul

Passing the context

The context can be passed as keyword arguments or as a dictionary.

simple2.py
from jinja2 import Template

tm = Template('My name is {{ name }} and I am {{ age }}')

print(tm.render(name='Peter', age=34))
print(tm.render({'name': 'Lucia', 'age': 28}))
print(tm.render(name='Robert'))

The template renders two variables: name and age. The first call passes them as keyword arguments, the second as a dictionary. The third call does not pass the age variable at all; by default, an undefined variable is rendered as an empty string.

$ python simple2.py
My name is Peter and I am 34
My name is Lucia and I am 28
My name is Robert and I am 

Jinja objects

We can work with objects in our template strings. The dot notation gives access to attributes and properties, and methods can be called with arguments.

objects.py
from jinja2 import Template


class Person:

    def __init__(self, first_name, last_name, born):
        self.first_name = first_name
        self.last_name = last_name
        self.born = born

    @property
    def full_name(self):
        return f'{self.first_name} {self.last_name}'

    def age(self, year):
        return year - self.born


person = Person('Peter', 'Novak', 1991)

tm = Template('{{ p.full_name }} was born in {{ p.born }} '
              'and is {{ p.age(2026) }} years old')

print(tm.render(p=person))

In the example, we define a Person class. In the template, we access the full_name property and the born attribute and call the age method with the current year.

$ python objects.py
Peter Novak was born in 1991 and is 35 years old

Dictionaries

Jinja allows a convenient dot notation to access data in Python dictionaries. The subscript syntax works as well.

dicts.py
from jinja2 import Template

person = {'name': 'Lucia', 'age': 28, 'items': 3}

tm = Template("{{ p.name }} {{ p['age'] }}")
print(tm.render(p=person))

tm = Template("dot: {{ p.items }}\nsubscript: {{ p['items'] }}")
print(tm.render(p=person))

For p.name, Jinja first looks for an attribute called name and then for an item with the key name. The subscript syntax p['age'] does it the other way around.

tm = Template("dot: {{ p.items }}\nsubscript: {{ p['items'] }}")

The order of the lookups matters when a key has the same name as a dictionary method. p.items finds the items method of the dictionary, while p['items'] returns the value of the key. Use the subscript syntax for keys such as items, keys, values, or get.

$ python dicts.py
Lucia 28
dot: <built-in method items of dict object at 0x78efead778c0>
subscript: 3

Undefined variables

The undefined option of the environment controls what happens when a template uses a variable that is not in the context.

undefined_vars.py
from jinja2 import Environment, StrictUndefined, UndefinedError

src = 'Hello {{ name }}, you have {{ count | default(0) }} messages'

env = Environment()
print(repr(env.from_string(src).render()))

env = Environment(undefined=StrictUndefined)
tm = env.from_string(src)
print(tm.render(name='Peter'))

try:
    tm.render()
except UndefinedError as e:
    print('error:', e)

The Environment is the central object of Jinja; it holds the configuration and creates templates. The from_string method compiles a template from a string.

With the default Undefined class, the missing name is rendered as an empty string, which can hide bugs. With StrictUndefined, printing an undefined variable raises UndefinedError. The default filter provides a fallback value; it works in both modes, so the count variable does not cause an error.

$ python undefined_vars.py
'Hello , you have 0 messages'
Hello Peter, you have 0 messages
error: 'name' is undefined

Jinja raw data

We can use the raw and endraw markers to escape Jinja delimiters.

raw_data.py
from jinja2 import Template

data = '''{% raw %}His name is {{ name }}{% endraw %}
His name is {{ name }}
Literal braces: {{ '{{' }} name {{ '}}' }}'''

tm = Template(data)

print(tm.render(name='Peter'))

By using the raw, endraw block, we escape the Jinja {{ }} syntax. It is printed in its literal meaning. The second line is rendered normally. For a single delimiter, we can also output a string literal such as {{ '{{' }}.

$ python raw_data.py
His name is {{ name }}
His name is Peter
Literal braces: {{ name }}

Jinja comments

Comments are written between {# and #} and are not included in the output.

comments.py
from jinja2 import Template

data = '''{# The greeting is shown to every user -#}
Hello {{ name }}!{# {{ secret }} is not rendered #}'''

tm = Template(data)

print(tm.render(name='Peter', secret='s3cret'))

A comment may span several lines and may contain other Jinja delimiters, which are not evaluated. The minus sign in -#} removes the newline that follows the comment; without it, the output would start with an empty line. The same whitespace control works with statements and expressions.

$ python comments.py
Hello Peter!

Jinja escape data

To escape characters such as <, >, or &, we can use the e filter or the escape function of the MarkupSafe library.

escape_data.py
from jinja2 import Template
from markupsafe import Markup, escape

data = '<a href="/">Today is a sunny day</a> & "warm"'

tm = Template('{{ data | e }}')
print(tm.render(data=data))

safe = escape(data)
print(safe)
print(type(safe).__name__)

print(Markup('<b>%s</b>') % '<i>bold?</i>')

The example escapes HTML special characters. Older Jinja versions re-exported escape and Markup from jinja2; since Jinja 3.1, they must be imported from markupsafe.

tm = Template('{{ data | e }}')

Using the e filter (an alias of escape), the data is escaped. Filters are applied with the | character.

safe = escape(data)
print(safe)
print(type(safe).__name__)

The escape function does the same. It returns a Markup object, a string subclass that marks the text as safe; it is not escaped again.

print(Markup('<b>%s</b>') % '<i>bold?</i>')

When a Markup string is formatted, the arguments are escaped, while the markup itself is kept.

$ python escape_data.py
&lt;a href=&#34;/&#34;&gt;Today is a sunny day&lt;/a&gt; &amp; &#34;warm&#34;
&lt;a href=&#34;/&#34;&gt;Today is a sunny day&lt;/a&gt; &amp; &#34;warm&#34;
Markup
<b>&lt;i&gt;bold?&lt;/i&gt;</b>

Autoescaping

Escaping every variable by hand is error-prone. With autoescaping enabled, Jinja escapes all printed values automatically.

autoescaping.py
from jinja2 import Environment

tm_src = '<p>{{ comment }}</p>\n<p>{{ note | safe }}</p>'

comment = '<script>alert("hacked")</script>'
note = '<em>Reviewed</em>'

env = Environment()
print(env.from_string(tm_src).render(comment=comment, note=note))
print()

env = Environment(autoescape=True)
print(env.from_string(tm_src).render(comment=comment, note=note))

A user comment contains a script. Without autoescaping, it is copied to the output as it is; in a web page, this is a cross-site scripting (XSS) vulnerability. With autoescape=True, the comment is escaped. The safe filter marks a value as trusted, so the note is printed unchanged in both cases. Use it only for data that does not come from users.

$ python autoescaping.py
<p><script>alert("hacked")</script></p>
<p><em>Reviewed</em></p>

<p>&lt;script&gt;alert(&#34;hacked&#34;)&lt;/script&gt;</p>
<p><em>Reviewed</em></p>

Autoescaping by file extension

The select_autoescape function enables autoescaping depending on the template file name.

select_escape.py
from jinja2 import Environment, FileSystemLoader, select_autoescape

env = Environment(loader=FileSystemLoader('templates'),
                  autoescape=select_autoescape())

data = {'title': 'Tom & Jerry', 'tag': '<cat>'}

print(env.get_template('page.html').render(data))
print(env.get_template('page.txt').render(data))

By default, select_autoescape turns autoescaping on for templates ending in .html, .htm, and .xml. The FileSystemLoader loads templates from the templates directory, which is relative to the current working directory.

templates/page.html
<h1>{{ title }}</h1>
<p>Tag: {{ tag }}</p>

The HTML template; the ampersand and the angle brackets are escaped.

templates/page.txt
Title: {{ title }}
Tag: {{ tag }}

The text template has the same content, but its values are printed unchanged.

$ python select_escape.py
<h1>Tom &amp; Jerry</h1>
<p>Tag: &lt;cat&gt;</p>
Title: Tom & Jerry
Tag: <cat>

Built-in filters

Filters modify the value of a variable. They can take arguments, and they can be chained; the output of one filter is the input of the next.

builtin_filters.py
from jinja2 import Template

data = '''{{ name | upper }}
{{ name | title }}
{{ words | join(', ') }}
{{ words | length }}
{{ words | sort | first }}
{{ price | round(1) }}
{{ "%.3f" | format(price) }}
{{ text | truncate(24) }}
{{ text | wordcount }}
{{ "  padded  " | trim | center(12) }}|
{{ 1234567 | filesizeformat }}'''

tm = Template(data)

print(tm.render(name='peter novak', words=['sky', 'cup', 'forest', 'atom'],
                price=12.4567,
                text='An old falcon soared high over the misty valley'))

The example applies several built-in filters. The upper and title filters change the case, join joins a sequence with a separator, length returns the number of items, and sort | first returns the alphabetically first word. round rounds a number, format applies a printf-style format, truncate shortens a text at a word boundary and adds an ellipsis, and wordcount counts the words. trim strips the whitespace, center centres the value in a field, and filesizeformat shows a number of bytes in a human-readable form (decimal units by default; binary=true uses KiB, MiB).

$ python builtin_filters.py
PETER NOVAK
Peter Novak
sky, cup, forest, atom
4
atom
12.5
12.457
An old falcon soared...
9
   padded   |
1.2 MB

Custom filters

A custom filter is a regular Python function registered in the filters dictionary of the environment.

custom_filters.py
from datetime import date

from jinja2 import Environment


def money(value, currency='EUR'):
    return f'{value:,.2f} {currency}'


def days_until(day, today):
    return (day - today).days


env = Environment()
env.filters['money'] = money
env.filters['days_until'] = days_until

tm = env.from_string('''Price: {{ price | money }}
Price: {{ price | money('USD') }}
Days to release: {{ release | days_until(today) }}''')

print(tm.render(price=1249.5, release=date(2026, 12, 24),
                today=date(2026, 10, 30)))

The value on the left side of the | is passed as the first argument of the function; the arguments in parentheses follow. The money filter has an optional currency, and days_until takes the reference date as its argument.

$ python custom_filters.py
Price: 1,249.50 EUR
Price: 1,249.50 USD
Days to release: 55

Jinja for expressions

The for expression is used to iterate over a data collection in a template. Now we do not use a simple string template anymore. We use a text file which is loaded with FileSystemLoader.

for_expr.py
from jinja2 import Environment, FileSystemLoader

persons = [
    {'name': 'Andrej', 'age': 34},
    {'name': 'Mark', 'age': 17},
    {'name': 'Thomas', 'age': 44},
    {'name': 'Lucy', 'age': 14},
    {'name': 'Robert', 'age': 23},
    {'name': 'Dragomir', 'age': 54},
]

env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('showpersons.txt')

print(template.render(persons=persons))

In this example, the template is the showpersons.txt file. The file is located in the templates directory. The data is a list of dictionaries.

env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('showpersons.txt')

We create an environment with a FileSystemLoader and get the template with the get_template method. The environment caches the compiled templates, so a template is parsed only once.

templates/showpersons.txt
{% for person in persons -%}
{{ person.name }} {{ person.age }}
{% endfor -%}

In the template file, we use the for expression to iterate over the collection. We show the person's name and age. The minus sign next to the % characters removes the whitespace, including the newline, after the tag, so the tags do not leave empty lines in the output.

$ python for_expr.py
Andrej 34
Mark 17
Thomas 44
Lucy 14
Robert 23
Dragomir 54

The loop variable

Inside a for loop, the special loop variable provides information about the iteration.

loop_var.py
from jinja2 import Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader('templates'),
                  trim_blocks=True, lstrip_blocks=True)
template = env.get_template('loop.txt')

print(template.render(colours=['red', 'green', 'blue', 'yellow'], empty=[]))

The environment is created with the trim_blocks and lstrip_blocks options; they remove the newline after a block tag and the whitespace before it. This allows us to write readable, indented templates.

templates/loop.txt
{% for colour in colours %}
{{ loop.index }}/{{ loop.length }} {{ colour }} {{ loop.cycle('odd', 'even') }}
  {%- if loop.first %} (first){% endif %}
  {%- if loop.last %} (last){% endif %}

{% endfor %}
{% for colour in colours | reverse %}{{ colour }}{{ ', ' if not loop.last }}{% endfor %}

{% for colour in colours if colour.startswith('b') or colour.startswith('y') %}
filtered: {{ colour }}
{% endfor %}
{% for item in empty %}
{{ item }}
{% else %}
no items
{% endfor %}

loop.index is the current iteration counted from 1 (use loop.index0 to count from 0), loop.length is the number of items, and loop.first and loop.last are true in the first and the last iteration. loop.cycle returns its arguments in turn. The second loop uses the reverse filter and adds a separator after every item but the last one.

The third loop filters the items with an if clause; unlike an if block inside the loop, the clause also affects the loop variable. The else block of the last loop is rendered when the sequence is empty. Jinja has no break or continue statements by default; filtering is the usual replacement.

$ python loop_var.py
1/4 red odd (first)
2/4 green even
3/4 blue odd
4/4 yellow even (last)
yellow, blue, green, red
filtered: blue
filtered: yellow
no items

Iterating over a dictionary

Dictionary items are unpacked into two loop variables.

dict_loop.py
from jinja2 import Template

capitals = {'Slovakia': 'Bratislava', 'Hungary': 'Budapest',
            'Poland': 'Warsaw'}

tm = Template('''{% for country, capital in capitals | dictsort -%}
{{ country }}: {{ capital }}
{% endfor %}''')

print(tm.render(capitals=capitals), end='')

The dictsort filter returns the dictionary items as (key, value) pairs sorted by the key. Without the filter, we would write capitals.items() and get the items in insertion order.

$ python dict_loop.py
Hungary: Budapest
Poland: Warsaw
Slovakia: Bratislava

Jinja conditionals

Conditionals are expressions that are evaluated when a certain condition is met.

conditionals.py
from jinja2 import Environment, FileSystemLoader

persons = [
    {'name': 'Andrej', 'age': 34},
    {'name': 'Mark', 'age': 17},
    {'name': 'Thomas', 'age': 44},
    {'name': 'Lucy', 'age': 14},
    {'name': 'Robert', 'age': 23},
    {'name': 'Dragomir', 'age': 54},
]

env = Environment(loader=FileSystemLoader('templates'),
                  trim_blocks=True, lstrip_blocks=True)
template = env.get_template('showminors.txt')

print(template.render(persons=persons), end='')

The example sorts the persons into minors, adults, and seniors; a minor is someone younger than 18.

templates/showminors.txt
{% for person in persons %}
    {% if person.age < 18 %}
{{ person.name }} is a minor
    {% elif person.age > 50 %}
{{ person.name }} is a senior
    {% else %}
{{ person.name }} is an adult
    {% endif %}
{% endfor %}

In the template, we use the if, elif, and else tags. Thanks to the trim_blocks and lstrip_blocks options, the indented block tags produce no output; only the text lines are printed.

$ python conditionals.py
Andrej is an adult
Mark is a minor
Thomas is an adult
Lucy is a minor
Robert is an adult
Dragomir is a senior

Whitespace control

By default, Jinja keeps all the whitespace around the tags. The next example compares the default output with the two ways of removing the whitespace.

whitespace.py
from jinja2 import Environment

src = '''<ul>
    {% for n in nums %}
    <li>{{ n }}</li>
    {% endfor %}
</ul>'''

dashes = '''<ul>
    {%- for n in nums %}
    <li>{{ n }}</li>
    {%- endfor %}
</ul>'''

nums = [1, 2]

print(Environment().from_string(src).render(nums=nums))
print('---')
env = Environment(trim_blocks=True, lstrip_blocks=True)
print(env.from_string(src).render(nums=nums))
print('---')
print(Environment().from_string(dashes).render(nums=nums))

In the first output, each tag line leaves its indentation and newline behind. The trim_blocks and lstrip_blocks options remove them for all block tags. The third template does the same with the minus sign: {%- removes all whitespace before the tag, including the preceding newline.

$ python whitespace.py
<ul>
    
    <li>1</li>
    
    <li>2</li>
    
</ul>
---
<ul>
    <li>1</li>
    <li>2</li>
</ul>
---
<ul>
    <li>1</li>
    <li>2</li>
</ul>

Jinja sum filter

Filters can be applied to collections. For instance, the sum filter sums data, and the min and max filters find the smallest and the largest item.

sum_filter.py
from jinja2 import Environment, FileSystemLoader

cars = [
    {'name': 'Audi', 'price': 23000},
    {'name': 'Skoda', 'price': 17300},
    {'name': 'Volvo', 'price': 44300},
    {'name': 'Volkswagen', 'price': 21300},
]

env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('sumprices.txt')

print(template.render(cars=cars))

We have a list of car dictionaries. Each dictionary has a price key; it is used to calculate the sum.

templates/sumprices.txt
The sum of car prices is {{ cars | sum(attribute='price') }}
The cheapest car is {{ (cars | min(attribute='price')).name }}
The most expensive car is {{ (cars | max(attribute='price')).name }}
Cars: {{ cars | map(attribute='name') | join(', ') }}

The sum filter is calculated from the price attribute. The min and max filters return the whole dictionary, so we access its name; the parentheses are needed because the dot binds tighter than the filter. The map filter extracts the names, which are then joined.

$ python sum_filter.py
The sum of car prices is 105900
The cheapest car is Skoda
The most expensive car is Volvo
Cars: Audi, Skoda, Volvo, Volkswagen

Selecting, sorting, and grouping

Jinja has filters for selecting, sorting, and grouping the items of a collection.

collections_filters.py
from jinja2 import Environment, FileSystemLoader

users = [
    {'name': 'John', 'city': 'Bratislava', 'active': True, 'salary': 1200},
    {'name': 'Lucia', 'city': 'Kosice', 'active': True, 'salary': 1650},
    {'name': 'Peter', 'city': 'Bratislava', 'active': False, 'salary': 980},
    {'name': 'Jana', 'city': 'Zilina', 'active': True, 'salary': 1430},
    {'name': 'Tomas', 'city': 'Kosice', 'active': False, 'salary': 2100},
]

env = Environment(loader=FileSystemLoader('templates'),
                  trim_blocks=True, lstrip_blocks=True)
template = env.get_template('users.txt')

print(template.render(users=users), end='')

The program renders a template with a list of users.

templates/users.txt
Active: {{ users | selectattr('active') | map(attribute='name') | join(', ') }}
Inactive: {{ users | rejectattr('active') | map(attribute='name') | join(', ') }}
High earners: {{ users | selectattr('salary', 'gt', 1500) | map(attribute='name') | list }}
By salary: {{ users | sort(attribute='salary', reverse=true) | map(attribute='name') | join(' > ') }}

{% for city, members in users | groupby('city') %}
{{ city }} ({{ members | length }}): {{ members | map(attribute='name') | join(', ') }}
{% endfor %}

The selectattr filter keeps the items whose attribute is true, and rejectattr keeps the others. With a test name and an argument, as in selectattr('salary', 'gt', 1500), the attribute is compared with a value. The sort filter sorts by an attribute; reverse=true sorts in descending order. Filters such as selectattr and map return generators; the list filter turns them into a list.

The groupby filter groups the items by an attribute; it sorts the items first, so the groups come out in alphabetical order. Each group is a (grouper, list) tuple, which we unpack in the loop.

$ python collections_filters.py
Active: John, Lucia, Jana
Inactive: Peter, Tomas
High earners: ['Lucia', 'Tomas']
By salary: Tomas > Lucia > Jana > John > Peter

Bratislava (2): John, Peter
Kosice (2): Lucia, Tomas
Zilina (1): Jana

Jinja tests

Tests check a value and return true or false. They are used with the is operator.

jinja_tests.py
from jinja2 import Environment


def is_prime(n):
    return n > 1 and all(n % d for d in range(2, int(n ** 0.5) + 1))


env = Environment(trim_blocks=True)
env.tests['prime'] = is_prime

tm = env.from_string('''{% for n in values %}
{{ n }}: {{ 'even' if n is even else 'odd' }}
{%- if n is divisibleby 3 %}, divisible by 3{% endif %}
{%- if n is prime %}, prime{% endif %}

{% endfor %}
nickname {{ 'is defined' if nickname is defined else 'is not defined' }}
tags {{ 'is' if tags is iterable else 'is not' }} iterable
{{ values | select('prime') | list }}
{{ values | reject('odd') | list }}''')

print(tm.render(values=[2, 7, 9, 12, 15], tags=('a', 'b')))

The template uses the built-in even, odd, divisibleby, defined, and iterable tests and a custom prime test, which is registered in the tests dictionary of the environment. A test with one argument can be written without parentheses, as in divisibleby 3.

The select and reject filters apply a test to each item of a sequence. The inline if/else expression works like Python's conditional expression.

$ python jinja_tests.py
2: even, prime
7: odd, prime
9: odd, divisible by 3
12: even, divisible by 3
15: odd, divisible by 3
nickname is not defined
tags is iterable
[2, 7]
[2, 12]

Assignments

Variables are created in templates with the set and with statements.

assignments.py
from jinja2 import Template

tm = Template('''{% set total = items | sum(attribute='qty') -%}
{% set vat = 0.23 -%}
Total items: {{ total }}
{% for item in items -%}
{% set line = item.qty * item.price -%}
{{ item.name }}: {{ line }} ({{ (line * (1 + vat)) | round(2) }} with VAT)
{% endfor -%}
{% with discount = 10 -%}
Discount: {{ discount }}%
{%- endwith %}
Discount outside with: {{ discount | default('none') }}
{% set ns = namespace(count=0) -%}
{% for item in items if item.qty > 1 %}{% set ns.count = ns.count + 1 %}{% endfor -%}
Items bought more than once: {{ ns.count }}''')

items = [
    {'name': 'pen', 'qty': 3, 'price': 1.5},
    {'name': 'notebook', 'qty': 1, 'price': 4.2},
    {'name': 'eraser', 'qty': 2, 'price': 0.8},
]

print(tm.render(items=items))

The set statement assigns a value to a template variable. A variable set inside a loop is local to the current iteration. The with statement creates an inner scope; the discount variable does not exist after endwith.

{% set ns = namespace(count=0) -%}
{% for item in items if item.qty > 1 %}{% set ns.count = ns.count + 1 %}{% endfor -%}

Because of the scoping rules, a counter assigned with set inside a loop would be lost after the loop. A namespace object solves this; its attributes can be changed from any scope.

$ python assignments.py
Total items: 6
pen: 4.5 (5.54 with VAT)
notebook: 4.2 (5.17 with VAT)
eraser: 1.6 (1.97 with VAT)
Discount: 10%
Discount outside with: none
Items bought more than once: 2

Macros

Macros are comparable with functions in programming languages. They are used to put frequently used pieces of a template into reusable units.

macros.py
from jinja2 import Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader('templates'),
                  trim_blocks=True, lstrip_blocks=True)
template = env.get_template('form.html')

print(template.render())

The program renders the form.html template.

templates/forms.html
{% macro input(name, value='', type='text') -%}
<input type="{{ type }}" name="{{ name }}" value="{{ value }}">
{%- endmacro %}

{% macro field(label, name) -%}
<label>{{ label }} {{ input(name, **kwargs) }}</label>
{%- endmacro %}

The forms.html file defines two macros. The input macro has a required and two optional parameters. The field macro calls input and passes it the extra keyword arguments, which are available in the special kwargs variable.

templates/form.html
{% import 'forms.html' as forms %}
{% from 'forms.html' import input %}
<form>
  {{ forms.field('User name', 'user') }}
  {{ forms.field('Password', 'pwd', type='password') }}
  {{ input('remember', 'yes', type='checkbox') }}
</form>

The import statement imports the macros file as a module; macros are called with the dot notation. The from ... import form imports a single macro into the template namespace.

$ python macros.py
<form>
  <label>User name <input type="text" name="user" value=""></label>
  <label>Password <input type="password" name="pwd" value=""></label>
  <input type="checkbox" name="remember" value="yes">
</form>

Including templates

The include statement renders another template and inserts the result into the current template.

include_tmpl.py
from jinja2 import Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader('templates'),
                  lstrip_blocks=True, trim_blocks=True,
                  keep_trailing_newline=True)
template = env.get_template('report.txt')

print(template.render(title='Monthly report', items=['sales', 'costs'],
                      lang='sk'), end='')

The keep_trailing_newline option keeps the final newline of a template, which Jinja removes by default. The included templates end with a newline, so the lines are not joined.

templates/report.txt
{% include 'header.txt' %}
{% for item in items %}
- {{ item }}
{% endfor %}
{% include 'footer.txt' ignore missing %}
{% include ['signature-' ~ lang ~ '.txt', 'signature.txt'] %}

The included templates have access to the variables of the current context; the header uses the title variable.

{% include 'footer.txt' ignore missing %}

With ignore missing, a missing template is not an error. There is no footer.txt file, so nothing is rendered.

{% include ['signature-' ~ lang ~ '.txt', 'signature.txt'] %}

When include gets a list, the first existing template is used. The ~ operator converts its operands to strings and concatenates them. There is no signature-sk.txt, so Jinja falls back to signature.txt.

templates/header.txt
=== {{ title | upper }} ===

The header template.

templates/signature.txt
-- generated by Jinja

The signature template.

$ python include_tmpl.py
=== MONTHLY REPORT ===
- sales
- costs
-- generated by Jinja

Jinja template inheritance

Template inheritance is a powerful feature that reduces code duplication and improves code organization. We define a base template from which we inherit in other template files. These template files override specific blocks of the base template file.

inheritance.py
from jinja2 import Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader('templates'), autoescape=True)
template = env.get_template('about.html')

print(template.render(content='Tom & Jerry'))

We render the about.html file. It inherits from the base.html file. Autoescaping is on, so the ampersand in the content is escaped.

templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>{% block title %}{% endblock %} - My site</title>
</head>
<body>
    <nav>{% block nav %}<a href="/">Home</a>{% endblock %}</nav>
    {% block content %}{% endblock %}
</body>
</html>

In the base.html file, we declare three blocks: title, nav, and content. These blocks are going to be filled with specific tags and text in the child templates. The nav block has a default content.

templates/about.html
{% extends 'base.html' %}

{% block title %}About{% endblock %}

{% block nav %}{{ super() }} | <a href="/about">About</a>{% endblock %}

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

The about.html template file inherits from base.html. It adds data specific to this page. We avoid code repetition; we do not repeat tags that are same for all pages, such as the html, head, and body tags.

{% extends 'base.html' %}

The inheritance is done with the extends tag. It should be the first tag of the template; text outside the blocks of a child template is not rendered.

{% block nav %}{{ super() }} | <a href="/about">About</a>{% endblock %}

The super function renders the content of the parent block, so we extend the navigation instead of replacing it.

<h1>{{ self.title() }}</h1>

A block can be printed more than once with the self variable; here, the page title is reused as the heading.

$ python inheritance.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>About - My site</title>
</head>
<body>
    <nav><a href="/">Home</a> | <a href="/about">About</a></nav>
    
    <h1>About</h1>
    <p>Tom &amp; Jerry</p>

</body>
</html>

Writing output to a file

The stream method renders a template piece by piece; the resulting TemplateStream can be written to a file with dump.

write_file.py
from jinja2 import Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader('templates'),
                  lstrip_blocks=True, trim_blocks=True,
                  keep_trailing_newline=True)

template = env.get_template('report.txt')
stream = template.stream(title='Weekly report', items=['orders', 'returns'],
                         lang='en')
stream.dump('weekly.txt', encoding='utf-8')

The program renders the report template from the include example and writes the result to weekly.txt. Streaming avoids building the whole output in memory, which helps with large documents. For small outputs, we can also call render and write the returned string.

$ python write_file.py
$ cat weekly.txt
=== WEEKLY REPORT ===
- orders
- returns
-- generated by Jinja

Native types

A template normally renders to a string. The NativeEnvironment returns native Python types instead.

native_types.py
from jinja2 import Environment
from jinja2.nativetypes import NativeEnvironment

src = '{{ values | sum }}'
values = [1, 2, 3]

out = Environment().from_string(src).render(values=values)
print(repr(out), type(out).__name__)

env = NativeEnvironment()
out = env.from_string(src).render(values=values)
print(repr(out), type(out).__name__)

out = env.from_string('{{ values | map("string") | list }}').render(values=values)
print(repr(out), type(out).__name__)

out = env.from_string('{{ x }} + {{ y }}').render(x=1, y=2)
print(repr(out), type(out).__name__)

With the regular environment, the sum is the string '6'. The NativeEnvironment evaluates the output with ast.literal_eval, so we get the integer 6 and a real list. When the template mixes expressions with text, as in {{ x }} + {{ y }}, the result is not a Python literal and stays a string.

$ python native_types.py
'6' str
6 int
['1', '2', '3'] list
'1 + 2' str

Sandboxed environment

Templates can call methods and access attributes of the objects passed to them. A template written by a user may therefore reach internals of the application. The SandboxedEnvironment restricts what templates can do.

sandbox_env.py
from jinja2.exceptions import SecurityError
from jinja2.sandbox import SandboxedEnvironment

env = SandboxedEnvironment()

print(env.from_string('{{ name.upper() }}').render(name='peter'))

user_template = "{{ ''.__class__.__mro__[1].__subclasses__() }}"

try:
    env.from_string(user_template).render()
except SecurityError as e:
    print('blocked:', e)

print(repr(env.from_string('{{ name.__class__ }}').render(name='peter')))

Calling ordinary methods, such as upper, is allowed. Access to attributes starting with an underscore is blocked. The unsafe attribute is replaced by an undefined value, which raises a SecurityError when it is used; here, when the template tries to subscript it. Printing the value directly renders an empty string.

The sandbox protects the application from untrusted templates, but it does not limit the time or memory a template uses. It is no substitute for not rendering user templates at all when that is possible.

$ python sandbox_env.py
PETER
blocked: access to attribute '__class__' of 'str' object is unsafe.
''

Jinja Flask example

In the next example, we create a simple Flask application that uses Jinja.

greet/app.py
from flask import Flask, render_template, request

app = Flask(__name__)


@app.route('/greet')
def greet():
    name = request.args.get('name', 'guest')
    return render_template('greet.html', name=name)

In this Flask application, we get the name of a user from the query string and pass it to the render_template function. The greet function reacts to the /greet path.

greet/templates/greet.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Greeting</title>
</head>
<body>
    <p>Hello {{ name }}!</p>
    <p>Path: {{ request.path }}</p>
</body>
</html>

This is the template file, located in the templates directory next to the application module. We add the name of the user with the {{ name }} syntax. Flask also passes objects such as request to each template.

Flask enables autoescaping for .html templates. In the transcript, we start the development server, send two requests with curl, and stop the server. The second name contains HTML tags, which are escaped in the response.

$ flask --app greet/app run &
 * Serving Flask app 'greet/app'
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
$ curl 'localhost:5000/greet?name=Peter'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Greeting</title>
</head>
<body>
    <p>Hello Peter!</p>
    <p>Path: /greet</p>
</body>
</html>
127.0.0.1 - - [30/Oct/2026 22:27:32] "GET /greet?name=Peter HTTP/1.1" 200 -
$ curl -G --data-urlencode 'name=<b>Peter</b>' localhost:5000/greet
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Greeting</title>
</head>
<body>
    <p>Hello &lt;b&gt;Peter&lt;/b&gt;!</p>
    <p>Path: /greet</p>
</body>
</html>
127.0.0.1 - - [30/Oct/2026 22:27:32] "GET /greet?name=<b>Peter</b> HTTP/1.1" 200 -

Source

Jinja documentation

In this article we have covered the Python Jinja module.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.