Show Menu
Cheatography

Jinja2 Cheat Sheet (DRAFT) by

Jinja document templating

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Jinja Tokens

{% ... %}
Control statements
{{ ... }}
Replac­ement expres­sions
{# ... #}
Comments

Whitespace control

+
Disable strip behavior to include extra whitespace
-
Remove whitespace around blocks
These modifiers can be added to the beginning or the end of a Jinja control token.
{%-
or
-%}
. In the case of
+
, the position controls where the trim is disabled. They can be applied to any control token
{%- %}
,
{{- }}
, or
{#- #}
.

Control blocks

{% if <st­ate­men­t> %}

...
{% elif <st­ate­men­t> %}

...
{% else %}

...
{% endif %}
{% for <it­em> in <li­st> [recur­sive] %}

...
{% endfor %}
{% block <na­me> [scoped] [required] %}

...
{% endblock %}
{% raw %}

...
{% endraw %}
{% macro <na­me>­(<a­rgs...>­) %}

...
{% endmacro %}
{% set <na­me> %}

...
{% endset %}
 

Filters

Variables can be modified with filters. To apply a filter use a pipe, '
|
'. For example,
{{ name|upper }}
.

Filters can be chained together. For example,
{{ name|striptags|title }}
will strip all HTML tags from
name
then convert it to Title case.

Some filters allow arguments. See the Jinja documentation for details.

Built-in filters

abs
forcee­scape
map
select
unique
attr
format
max
selectattr
upper
batch
groupby
min
slice
urlencode
capitalize
indent
pprint
sort
urlize
center
int
random
string
wordcount
default
items
reject
striptags
wordwrap
dictsort
join
rejectattr
sum
xmlattr
escape
last
replace
title
filesi­zef­ormat
length
reverse
tojson
first
list
round
trim
float
lower
safe
truncate

Assign­ments and macros

Variable assignment
Simple variables can be assigned by using the
set
block:
{% set variab­le=­'value' %}
Block assign­ments
Templated blocks can be assigned to variable names by using a
set
block.
{% set reply %}
    Thanks for your message:
    {{ message }}.
{% endset %}
 

Loop special variables

loop.index
The current iteration of the loop. (1 indexed)
loop.i­ndex0 
The current iteration of the loop. (0 indexed)
loop.r­evindex
The number of iterations from the end of the loop (1 indexed)
loop.r­evi­ndex0
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.l­ength
The number of items in the sequence.
loop.cycle
A helper function to cycle between a list of sequences.
loop.depth
Indicates how deep in a recursive loop the rendering currently is. Starts at level 1
loop.d­epth0
Indicates how deep in a recursive loop the rendering currently is. Starts at level 0
loop.p­revitem
The item from the previous iteration of the loop. Undefined during the first iteration.
loop.n­extitem
The item from the following iteration of the loop. Undefined during the last iteration.
loop.changed(*val)
True if previously called with a different value (or not called at all).