Learn, create and have fun with Python

Jinja templates: Basics

Basic Jinja templates syntax

{% … %} Statements. Add control flow and looping inside the templates

{{ … }} Expressions. Evaluate expression, variable or function call

{# … #} Comments

# … ## Line Statements

{% raw %} {% endraw %} escaping, as well as ‘ ‘ in {{ ‘{{‘ }} * {% raw -%} cleans all preceding spaces and newlines.

Code snippets

    {{ "User is logged in" if loggedin else "User is not logged in" }}  # oneliner
    {# This is comment #}
    {% set weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] %}  # set var

    # iterate through list
    {% for day in weekdays %}
        <p> 'Today is {{day}}'</p>
    {% endfor %}

    # set dict and iterate through it
    {% set user = { 'name': 'Socrates', 'city': 'Athens', 'occupation': 'philosopher' } %}
    {% for key, value in user.items() %}
        <li>{{ key }} : {{ value }}</li>
    {% endfor %}

    # set list and iterate using loop.index (as enum)
    {% set user_list = ['Socrates', 'Plato', ' Xenophon', 'Aristotle', ' Diogenes'] %}
    {% for user in user_list  %}
        <li>{{ loop.index }} - "Hello, {}!".format(user)</li>
    {% endfor %}

loop methods

Variable Description
loop.index0 same as loop.index but 0 indexed i.e it starts counting iteration from 0 instead of 1.
loop.revindex returns the iteration from the end of the loop (1 indexed).
loop.revindex0 same as loop.revindex but 0 indexed.
loop.first returns True if the current iteration is the first iteration. Otherwise False.
loop.last returns True if the current iteration is the last iteration. Otherwise False.
loop.length returns the length of the sequence the for loop is iterating over.

Scope limiting. WITH statement

To create a new inner scope use with. Variables set within this scope are not visible outside of the scope.

{% with %}
    {% set user = 'Crito' %}
    {{ user }}  # user is Crito inside this statement
{% endwith %}
# user Crito is discarded outside the statement


Filters modify the variables before they are rendered. Multiple filters can be chained. The output of one filter is applied to the next.


    {{ user|default('guest')|capitalize|center }}
    # if user is not set, user = "guest"|"Guest"|center "Guest" in a filed with width 80

default(value, default_value=”, boolean=False) If the value is undefined it will return the passed default value, otherwise the value of the variable.

capitalize(s) Capitalize a value. The first character will be uppercase, all others lowercase.

center(value, width=80) Centers the value in a field of a given width.

More on Jinja templates builtin filters


Tests are used to check a variable against a common expression.

var is test

    {% if user is defined %}
    <p>{{user}} has joined the discussion</p>
    {% else %}
    <p>Virtue is sufficient for happiness - Socrates</p>
    {% endif %}

More on Jinja templates builtin tests

Global functions


lipsum(n=5, html=True, min=20, max=100)

Generates some lorem ipsum for the template. By default, HTML of 5 paragraphs, each between 20 and 100 words long.

More on Jinja templates global functions


Macros in Jinja templates is reusable code with name (similar to a functions in Python).

{% macro input(user, value='', type='text', size=20) -%}
{%- endmacro %}

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

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

Or using {% call macro_name(‘macro params’) %} {% endcall %}




Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top