moonpug
Reference

BtIns

What a template can reach without being handed anything: the filters, tests and globals, and the statements that shape a page. Every live example below is rendered by the same engine this site is built from — edit nothing, the output is the real one.

Filters

Seventy-nine filters, written after a value with |. Aliases are noted where they stand in for another.

Text and letters

filter capitalize

Capitalise the first character and lowercase the rest.

value|capitalize
template
{{ "hello WORLD"|capitalize }}
output
Hello world

filter capfirst

Capitalise only the first character, leaving the rest.

value|capfirst
template
{{ "hello"|capfirst }}
output
Hello

filter center

Centre the text in a field of the given width.

value|center(width)
width int
field width
template
{{ "hi"|center(10) }}
output
hi

filter cut

Remove every occurrence of a substring.

value|cut(arg)
arg string
text to remove
template
{{ "a-b-c"|cut("-") }}
output
abc

filter escape

Escape HTML so the text is safe to write. Markup is left as it stands.

value|escape
template
{{ "<b>"|escape }}
output
&lt;b&gt;

filter e

An alias of escape.

value|e
template
{{ "<b>"|e }}
output
&lt;b&gt;

filter escapejs

Escape text so it is safe inside a JavaScript string.

value|escapejs
template
{{ "a'b<c"|escapejs }}
output
a\u0027b\u003Cc

filter forceescape

Escape even text already marked safe.

value|forceescape
template
{{ ("<b>"|safe)|forceescape }}
output
&lt;b&gt;

filter indent

Indent each line (after the first unless first) by a width.

value|indent(width, first, blank)
width int or string
spaces or a literal prefix
first bool
indent the first line too
blank bool
indent blank lines too
template
{{ "a\nb"|indent(2) }}
output
a b

filter linebreaks

Turn newlines into paragraphs and line breaks, returned as safe HTML.

value|linebreaks
template
{{ "one\n\ntwo"|linebreaks }}
output
<p>one</p> <p>two</p>

filter linebreaksbr

Turn newlines into line breaks, returned as safe HTML.

value|linebreaksbr
template
{{ "a\nb"|linebreaksbr }}
output
a<br>b

filter linenumbers

Prefix every line with its one-based number.

value|linenumbers
template
{{ "a\nb\nc"|linenumbers }}
output
1. a 2. b 3. c

filter lower

Lowercase the text.

value|lower
template
{{ "HELLO"|lower }}
output
hello

filter markdown

Read the text as Markdown and write it as HTML, the conversion an md template ends with.

value|markdown(safe)
safe bool
escape HTML in the text, true unless you say otherwise
template
{{ "## From a string"|markdown }}
output
<h2>From a string</h2>

filter replace

Replace occurrences of old with new, at most count times.

value|replace(old, new, count)
old string
text to find
new string
replacement
count int
most replacements, -1 for all
template
{{ "a-b-c"|replace("-", " ") }}
output
a b c

filter safe

Mark the text safe; it passes through without escaping.

value|safe
template
{{ ("<b>"|safe) }}
output
<b>

filter spaceless

Remove the whitespace between tags.

value|spaceless
template
{{ "<a>  </a>"|spaceless }}
output
&lt;a&gt;&lt;/a&gt;

filter string

Cast the value to text.

value|string
template
{{ 7|string }}
output
7

filter striptags

Strip tags and decode entities, collapsing whitespace.

value|striptags
template
{{ "<b>hi</b>"|striptags }}
output
hi

filter title

Title-case the text: capitalise each word.

value|title
template
{{ "hello world"|title }}
output
Hello World

filter trim

Strip surrounding characters (default whitespace).

value|trim(chars)
chars string
characters to strip
template
{{ "  hi  "|trim }}
output
hi

filter slugify

An ASCII slug: accents dropped, letters and digits kept, spaces and dashes to one dash, lowercase.

value|slugify
template
{{ "Un éléphant à l'orée!"|slugify }}
output
un-elephant-a-loree

filter truncatechars

Cut to a number of characters, ending with an ellipsis; combining marks do not count.

value|truncatechars(arg)
arg int
most characters
template
{{ "Testing, testing"|truncatechars(8) }}
output
Testing…

filter truncate

Cut to a length, ending with an ellipsis, keeping whole words unless killwords.

value|truncate(length, killwords, end, leeway)
length int
maximum length
killwords bool
cut mid-word
end string
the ending, … by default
leeway int
grace before cutting
template
{{ "a long sentence about the weather"|truncate(20) }}
output
a long sentence...

filter upper

Uppercase the text.

value|upper
template
{{ "héllo"|upper }}
output
HÉLLO

filter wordcount

Count the words.

value|wordcount
template
{{ "the quick brown"|wordcount }}
output
3

filter wordwrap

Wrap the text at a column width.

value|wordwrap(width, break_long_words, wrapstring, break_on_hyphens)
width int
column width
break_long_words bool
split long words
wrapstring string
line separator
break_on_hyphens bool
break on hyphens
template
{{ "one two three four five"|wordwrap(10) }}
output
one two three four five

filter addslashes

Escape quotes and backslashes for a JavaScript string.

value|addslashes
template
{{ "it's"|addslashes }}
output
it\&#39;s

filter iriencode

Percent-encode an IRI for use in a URL.

value|iriencode
template
{{ "a path/c?d"|iriencode }}
output
a%20path/c?d

filter phone2numeric

Map letters to the digits of a telephone keypad.

value|phone2numeric
template
{{ "0800cafe"|phone2numeric }}
output
08002233

filter format

Fill % placeholders with positional or named arguments.

value|format(*args, **named)
args values
positional %s, %d, …
named mapping
named %(name)s
template
{{ "%s = %s"|format("x", 1) }}
output
x = 1

Numbers

filter abs

The absolute value of a number.

value|abs
template
{{ -7|abs }}
output
7

filter add

Add a number, or concatenate strings and lists.

value|add(arg)
arg value
the value to add or join
template
{{ 10|add(5) }}
output
15

filter filesizeformat

Format a count of bytes as a human size.

value|filesizeformat(binary)
binary bool
use 1024-based units
template
{{ 1234567|filesizeformat }}
output
1.2 MB

filter float

Parse a number or string as a floating point value.

value|float(default)
default float
fallback when not a number
template
{{ "3.14"|float }}
output
3.14

filter floatformat

Format a number to fixed places, Django style (g groups thousands, u ungroups).

value|floatformat(arg)
arg string or int
places; -1 drops empty fraction; default -1
template
{{ 3.14159|floatformat(2) }}
output
3.14

filter get_digit

Return the nth digit of an integer, counting from the right; 1 is the units digit.

value|get_digit(arg)
arg int
which digit
template
{{ 12345|get_digit(2) }}
output
4

filter int

Parse a number or string as an integer, in a given base.

value|int(default, base)
default int
fallback when not a number
base int
number base, 10 by default
template
{{ "42"|int }}
output
42

filter round

Round a number: common, ceil or floor, to a number of places.

value|round(precision, method)
precision int
decimal places
method string
common, ceil or floor
template
{{ 3.14159|round(2) }}
output
3.14

filter widthratio

Scale a value to a width: the value over the maximum, times the width, rounded half to even.

value|widthratio(max_value, max_width)
max_value number
the value that fills the width
max_width int
the width, 100 by default
template
{{ 175|widthratio(200) }}
output
88

filter sum

Add the items, or a named field of each.

value|sum(attribute, start)
attribute string
field to sum
start value
starting value
template
{{ items|sum(attribute="n") }}
data
{"items":[{"n":1},{"n":2},{"n":3}]}
output
6

Lists and tables

filter batch

Group items into rows of a given size, padding the last with fill_with.

value|batch(linecount, fill_with)
linecount int
items per row
fill_with value
padding for the last row
template
{{ [1,2,3,4,5]|batch(2)|list }}
output
[[1, 2], [3, 4], [5]]

filter dictsort

Sort a mapping into (key, value) pairs, by key, value or with a case-sensitive order.

value|dictsort(case_sensitive, by, reverse)
case_sensitive bool
compare letters as written
by string
key or value
reverse bool
reverse the order
template
{{ {"b":2,"a":1}|dictsort|list }}
output
[(&#39;a&#39;, 1), (&#39;b&#39;, 2)]

filter first

The first item of a sequence.

value|first
template
{{ [1,2,3]|first }}
output
1

filter groupby

Group items that share an attribute, each group read as grouper and list.

value|groupby(attribute, default, case_sensitive)
attribute string
field to group by
default value
value for missing fields
case_sensitive bool
compare letters as written
template
{{ users|groupby("kind")|map(attribute="grouper")|join(", ") }}
data
{"users":[{"kind":"a","name":"x"},{"kind":"b","name":"y"},{"kind":"a","name":"z"}]}
output
a, b

filter items

A mapping's entries as (key, value) pairs.

value|items
template
{{ {"a":1,"b":2}|items|list }}
output
[(&#39;a&#39;, 1), (&#39;b&#39;, 2)]

filter join

Join items with a separator, or a named field of each.

value|join(d, attribute)
d string
the separator
attribute string
field to join
template
{{ ["a","b","c"]|join(", ") }}
output
a, b, c

filter last

The last item of a sequence.

value|last
template
{{ [1,2,3]|last }}
output
3

filter length

The length: characters of a string, items of a list, keys of a mapping.

value|length
template
{{ [1,2,3]|length }}
output
3

filter count

An alias of length.

value|count
template
{{ "hello"|count }}
output
5

filter list

Turn the value into a list.

value|list
template
{{ "abc"|list }}
output
[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]

filter map

Apply a filter to each item, or pull a named field out of each.

value|map(attribute, default, filter)
attribute string
field to read
default value
value for missing fields
filter string
a filter to apply to each item
template
{{ users|map(attribute="name")|join(", ") }}
data
{"users":[{"name":"Ada"},{"name":"Grace"}]}
output
Ada, Grace

filter max

The largest item, or the largest by a field.

value|max(attribute, case_sensitive)
attribute string
field to compare
case_sensitive bool
compare letters as written
template
{{ [3,1,2]|max }}
output
3

filter min

The smallest item, or the smallest by a field.

value|min(attribute, case_sensitive)
attribute string
field to compare
case_sensitive bool
compare letters as written
template
{{ [3,1,2]|min }}
output
1

filter pprint

A readable, Python-style print of a value.

value|pprint
template
{{ {"a":[1,2],"b":3}|pprint }}
output
{&#39;a&#39;: [1, 2], &#39;b&#39;: 3}

filter random

One item, chosen so the same page renders the same way twice.

value|random
template
{{ [1,2,3]|random }}
output
2

filter reject

Drop items that pass a test; with no test, drop the untruthy.

value|reject(test, args)
test string
a test name
args values
the test's arguments
template
{{ [1,2,3,4]|reject("odd")|list }}
output
[2, 4]

filter rejectattr

Drop items whose field fails a test.

value|rejectattr(attribute, test, args)
attribute string
field to test
test string
a test name
args values
the test's arguments
template
{{ items|rejectattr("shown")|list }}
data
{"items":[{"shown":true},{"shown":false}]}
output
[{&#39;shown&#39;: False}]

filter reverse

Reverse a list, or the characters of a string.

value|reverse
template
{{ [1,2,3]|reverse|list }}
output
[3, 2, 1]

filter select

Keep items that pass a test; with no test, keep the truthy.

value|select(test, args)
test string
a test name
args values
the test's arguments
template
{{ [1,2,3,4]|select("odd")|list }}
output
[1, 3]

filter selectattr

Keep items whose field passes a test.

value|selectattr(attribute, test, args)
attribute string
field to test
test string
a test name
args values
the test's arguments
template
{{ items|selectattr("shown")|list }}
data
{"items":[{"shown":true},{"shown":false}]}
output
[{&#39;shown&#39;: True}]

filter slice

Split into a number of slices, padding the last with fill_with.

value|slice(slices, fill_with)
slices int
how many slices
fill_with value
padding for the last slice
template
{{ [1,2,3,4,5]|slice(2)|list }}
output
[[1, 2, 3], [4, 5]]

filter sort

Sort items, by a field, with a case-sensitive or reversed order.

value|sort(reverse, case_sensitive, attribute)
reverse bool
reverse the order
case_sensitive bool
compare letters as written
attribute string
field to sort by
template
{{ ["b","a","c"]|sort|list }}
output
[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]

filter unique

Drop repeated items, by value or by a field.

value|unique(case_sensitive, attribute)
case_sensitive bool
compare letters as written
attribute string
field to compare
template
{{ [1,2,2,3]|unique|list }}
output
[1, 2, 3]

filter attr

Read a named attribute of a host object.

value|attr(name)
name string
the attribute
template
{% set ns = namespace(city="Rome") %}{{ ns|attr("city") }}
output
Rome

Choosing a value

filter default

A fallback when the value is undefined, or false under boolean.

value|default(default_value, boolean)
default_value value
what to use instead
boolean bool
also replace a false value
template
{{ missing|default("none") }}
output
none

filter d

An alias of default.

value|d(default_value, boolean)
default_value value
what to use instead
boolean bool
also replace a false value
template
{{ missing|d("none") }}
output
none

filter default_if_none

A fallback used only when the value is null.

value|default_if_none(arg)
arg value
what to use instead
template
{{ none|default_if_none("none") }}
output
none

Markup and URLs

filter urlencode

Percent-encode a string, or a mapping or pairs as a query string.

value|urlencode
template
{{ {"q":"a b"}|urlencode }}
output
q=a+b

filter urlize

Turn web addresses and emails into anchor tags.

value|urlize(trim_url_limit, nofollow, target, rel, extra_schemes)
trim_url_limit int
shorten shown links
nofollow bool
add rel=nofollow
target string
the anchor target
rel string
extra rel words
extra_schemes list
more URI schemes to link
template
{{ "visit http://example.com"|urlize }}
output
visit <a href="http://example.com" rel="noopener">http://example.com</a>

filter xmlattr

Build a string of attributes from a mapping, as safe markup.

value|xmlattr(autospace)
autospace bool
a leading space, on by default
template
{{ {"class":"x","id":5}|xmlattr }}
output
class="x" id="5"

filter tojson

Serialise a value to JSON safe inside a script tag.

value|tojson(indent)
indent int
spaces to indent
template
{{ {"a":1}|tojson }}
output
{"a": 1}

filter json_script

Wrap JSON in a script tag, optionally with an id.

value|json_script(element_id)
element_id string
the tag's id
template
{{ {"a":1}|json_script("data") }}
output
<script id="data" type="application/json">{"a": 1}</script>

filter truncatewords

Cut to a number of words, ending with an ellipsis.

value|truncatewords(arg)
arg int
most words
template
{{ "one two three four"|truncatewords(2) }}
output
one two …

filter truncatechars_html

Cut marked-up text to a number of characters, closing the elements the cut leaves open; the result is markup when the input is trusted.

value|truncatechars_html(arg)
arg int
most characters, tags aside
template
{{ ("<p>one <b>two</b> three</p>"|safe)|truncatechars_html(8) }}
output
<p>one <b>two</b>…</p>

filter truncatewords_html

Cut marked-up text to a number of words, closing the elements the cut leaves open; the result is markup when the input is trusted.

value|truncatewords_html(arg)
arg int
most words
template
{{ ("<p>one <b>two</b> three</p>"|safe)|truncatewords_html(2) }}
output
<p>one <b>two</b> …</p>

filter unordered_list

Render a list of items and nested lists as HTML ul elements.

value|unordered_list
template
{{ tree|unordered_list }}
data
{"tree":["first",["child one","child two"],"last"]}
output
<li>first <ul> <li>child one</li> <li>child two</li> </ul> </li> <li>last</li>

filter ljust

Left-justify the text in a field of the given width.

value|ljust(arg)
arg int
field width
template
{{ "hi"|ljust(5) }}
output
hi

filter rjust

Right-justify the text in a field of the given width.

value|rjust(arg)
arg int
field width
template
{{ "hi"|rjust(5) }}
output
hi

filter yesno

Map true, false and null to words, comma-separated.

value|yesno(arg)
arg string
yes,no,maybe (maybe optional)
template
{{ ok|yesno }}
data
{"ok":true}
output
yes

filter pluralize

Add a suffix (or two, comma-separated) based on a count.

value|pluralize(arg)
arg string
suffix, or singular,plural
template
{{ count|pluralize }}
data
{"count":3}
output
s

Dates and times

filter date

Format a date with Django's letters; a time letter is refused.

value|date(arg)
arg string
a format or a named format such as DATE_FORMAT
template
{{ d|date("Y-m-d") }}
data
{"d":"2026-05-04"}
output
2026-05-04

filter time

Format a time with Django's letters; a date letter is ignored.

value|time(arg)
arg string
a format or TIME_FORMAT
template
{{ t|time("H:i") }}
data
{"t":"2026-05-04T13:45:00"}
output
13:45

filter timesince

Words for the span from a date to now (a date you supply, templates read no clock).

value|timesince(now, depth)
now date
the moment to measure to
depth int
most adjacent units, 2 by default
template
{{ d|timesince(now) }}
data
{"d":"2026-01-01","now":"2026-05-04"}
output
4 months

filter timeuntil

Words for the span from now to a date.

value|timeuntil(now, depth)
now date
the moment to measure to
depth int
most adjacent units, 2 by default
template
{{ d|timeuntil(now) }}
data
{"d":"2026-05-04","now":"2026-01-01"}
output
4 months

Tests

Thirty-nine tests, written after a value with is. Many comparison names are aliases of the symbol forms.

Type

test none

True when the value is null.

value is none
template
{{ none is none }}
output
True

test boolean

True when the value is a boolean.

value is boolean
template
{{ true is boolean }}
output
True

test true

True when the value is the boolean true.

value is true
template
{{ true is true }}
output
True

test false

True when the value is the boolean false.

value is false
template
{{ false is false }}
output
True

test integer

True when the value is an integer.

value is integer
template
{{ 3 is integer }}
output
True

test float

True when the value is a floating point number.

value is float
template
{{ 3.0 is float }}
output
True

test number

True when the value is a number (integer, float or boolean).

value is number
template
{{ 3 is number }}
output
True

test string

True when the value is text or safe markup.

value is string
template
{{ "x" is string }}
output
True

test mapping

True when the value is a mapping.

value is mapping
template
{{ {} is mapping }}
output
True

test sequence

True when the value is a string, list, tuple or mapping.

value is sequence
template
{{ [1,2] is sequence }}
output
True

test iterable

True when the value can be looped over.

value is iterable
template
{{ "ab" is iterable }}
output
True

test callable

True when the value can be called, like a global function.

value is callable
template
{{ range is callable }}
output
True

test escaped

True when the value is markup already safe to write.

value is escaped
template
{{ ("<b>"|safe) is escaped }}
output
True

Numbers and comparison

test odd

True when a number is odd.

value is odd
template
{{ 7 is odd }}
output
True

test even

True when a number is even.

value is even
template
{{ 4 is even }}
output
True

test divisibleby

True when a number divides by the argument.

value is divisibleby(n)
n number
the divisor
template
{{ 9 is divisibleby(3) }}
output
True

test ==

True when the value equals the other. Also eq and equalto.

value == other
other value
what to compare against
template
{{ 3 == 3 }}
output
True

test eq

An alias of ==.

value is eq other
other value
what to compare against
template
{{ 3 is eq 3 }}
output
True

test equalto

An alias of ==.

value is equalto other
other value
what to compare against
template
{{ 3 is equalto 3 }}
output
True

test !=

True when the value differs from the other. Also ne.

value != other
other value
what to compare against
template
{{ 3 != 4 }}
output
True

test ne

An alias of !=.

value is ne other
other value
what to compare against
template
{{ 3 is ne 4 }}
output
True

test <

True when the value is less than the other. Also lt and lessthan.

value < other
other value
what to compare against
template
{{ 3 < 4 }}
output
True

test lt

An alias of <.

value is lt other
other value
what to compare against
template
{{ 3 is lt 4 }}
output
True

test lessthan

An alias of <.

value is lessthan other
other value
what to compare against
template
{{ 3 is lessthan 4 }}
output
True

test >

True when the value is greater than the other. Also gt and greaterthan.

value > other
other value
what to compare against
template
{{ 3 > 2 }}
output
True

test gt

An alias of >.

value is gt other
other value
what to compare against
template
{{ 3 is gt 2 }}
output
True

test greaterthan

An alias of >.

value is greaterthan other
other value
what to compare against
template
{{ 3 is greaterthan 2 }}
output
True

test <=

True when the value is at most the other. Also le.

value <= other
other value
what to compare against
template
{{ 3 <= 3 }}
output
True

test le

An alias of <=.

value is le other
other value
what to compare against
template
{{ 3 is le 3 }}
output
True

test >=

True when the value is at least the other. Also ge.

value >= other
other value
what to compare against
template
{{ 3 >= 3 }}
output
True

test ge

An alias of >=.

value is ge other
other value
what to compare against
template
{{ 3 is ge 3 }}
output
True

Strings

test lower

True when text is all lowercase.

value is lower
template
{{ "abc" is lower }}
output
True

test upper

True when text is all uppercase.

value is upper
template
{{ "ABC" is upper }}
output
True

Identity and membership

test sameas

True when the two values are the same object or equal value.

value is sameas other
other value
the other value
template
{% set a = [1] %}{{ a is sameas a }}
output
True

test in

True when the value is a member of the container.

value is in container
container value
where to look
template
{{ "a" in ["a","b"] }}
output
True

Existence

test defined

True when the name resolved to a value.

value is defined
template
{% set present = 1 %}{{ present is defined }}
output
True

test undefined

True when the name resolved to nothing.

value is undefined
template
{{ missing is undefined }}
output
True

test filter

True when a filter of the given name is registered.

value is filter
template
{{ "upper" is filter }}
output
True

test test

True when a test of the given name is registered.

value is test
template
{{ "odd" is test }}
output
True

Globals

Eleven names every template sees without being passed in. _ is an alias of gettext.

global range

Build a list of integers, Python's range.

range(stop) · range(start, stop) · range(start, stop, step)
start int
first value, 0 by default
stop int
one past the last
step int
the step, 1 by default
template
{{ range(1, 4)|list }}{{ range(0, 10, 2)|list }}
output
[1, 2, 3][0, 2, 4, 6, 8]

global dict

Build a mapping from pairs, a mapping or named arguments.

dict(pairs) · dict(a=1, b=2)
pairs sequence
a list of [key, value]
named values
keys and values
template
{{ dict(a=1, b=2)|items|list }}
output
[(&#39;a&#39;, 1), (&#39;b&#39;, 2)]

global lipsum

Generate pseudo-Latin filler text, the same page twice, as safe HTML or plain text.

lipsum(n, html, min, max)
n int
paragraphs, 5 by default
html bool
wrap in <p>, true by default
min int
shortest word count
max int
longest word count
template
{{ lipsum(n=1, min=5, max=8) }}
output
<p>Aptent leo luctus nonummy taciti vitae.</p>

global cycler

Cycle through items: current names the present item, next advances.

cycler(*items)
items values
the values to cycle
template
{% set c = cycler("odd","even") %}{{ c.next() }}{{ c.next() }}{{ c.next() }}
output
oddevenodd

global joiner

A separator that prints nothing the first time and the separator after.

joiner(sep)
sep string
the separator, ", " by default
template
{% set j = joiner(", ") %}{% for x in ["a","b","c"] %}{{ j() }}{{ x }}{% endfor %}
output
a, b, c

global namespace

A mapping whose fields a template may assign from inside a loop or block.

namespace(**fields)
fields values
initial fields
template
{% set ns = namespace(n=0) %}{% for i in [1,2,3] %}{% set ns.n = ns.n + i %}{% endfor %}{{ ns.n }}
output
6

global gettext

Translate a message through the translation seam; with no seam the text stands.

gettext(message) · _(message)
message string
the message to translate
template
{{ gettext("Hello") }} {{ _("World") }}
output
Hello World

global _

An alias of gettext.

_(message)
message string
the message to translate
template
{{ _("Hello") }}
output
Hello

global ngettext

Translate a singular or plural message by a count.

ngettext(singular, plural, count)
singular string
one form
plural string
many form
count number
the count
template
{{ ngettext("%(num)d apple", "%(num)d apples", n) }}
data
{"n":2}
output
2 apples

global pgettext

Translate a message within a context.

pgettext(context, message)
context string
the message context
message string
the message to translate
template
{{ pgettext("menu", "Open") }}
output
Open

global npgettext

Translate a singular or plural message within a context.

npgettext(context, singular, plural, count)
context string
the message context
singular string
one form
plural string
many form
count number
the count
template
{{ npgettext("file", "%(num)d file", "%(num)d files", n) }}
data
{"n":2}
output
2 files

global templatetag

Write the characters of a tag as text, by Django's name for each.

templatetag(tag)
tag string
openblock, closeblock, openvariable, closevariable, openbrace, closebrace, opencomment or closecomment
template
{{ templatetag("openblock") }} if x {{ templatetag("closeblock") }}
output
{% if x %}

global query_string

Build a query string from mappings and named values; null drops a key, a list repeats it.

query_string(*mappings, **values)
mappings mapping
the parameters to start from
values values
the parameters to set
template
{{ query_string(page=2, q="a b") }}
output
?page=2&amp;q=a+b

global url

The address a program gives a route. Registered by the program through Env::add_host, so it is shown here rather than run.

url(name, *args, **kwargs)
name string
the route's name
args values
what fills the route
template
{{ url("post", 42) }}

Needs the program's routes: register url through Env::add_host(host=…). The Guide shows a whole host.

global static

Where a static file is served from. Registered by the program through Env::add_host.

static(path)
path string
the file under the static root
template
{{ static("css/site.css") }}

Needs the program's static prefix: register asset through Env::add_host(host=…).

global static_prefix

The prefix static files sit under, on its own. Registered by the program.

static_prefix()
template
{{ static_prefix() }}

Needs the program's static prefix: register asset_prefix through Env::add_host(host=…).

global media_prefix

The prefix uploaded files sit under. Registered by the program.

media_prefix()
template
{{ media_prefix() }}

Needs the program's media prefix: register media_prefix through Env::add_host(host=…).

global csrf_token

The token a form carries, as markup. Registered by the program.

csrf_token()
template
{{ csrf_token() }}

Needs the program's token: register csrf_token through Env::add_host(host=…).

global now

The moment to render, written with Django's date letters. Registered by the program: templates read no clock.

now(format)
format string
a format, or a named one such as DATE_FORMAT
template
{{ now("Y-m-d H:i") }}

Needs the program's clock: register now through Env::add_host(host=…).

Statements

The tags that shape a template. Most run live below through the same engine this site ships; a few that need a loader or a host object are shown with their syntax.

Flow control

statement if

Branch on a condition; elif adds a clause, else the fallback.

{% if cond %}…{% elif cond %}…{% else %}…{% endif %}
template
{% if n > 2 %}big{% elif n == 2 %}two{% else %}small{% endif %}
data
{"n":2}
output
two

statement for

Loop over items. The else runs when there were none; break and continue work inside. The loop variable holds index, index0, revindex, first, last, length, depth, previtem, nextitem, cycle(…) and changed(…); a recursive loop calls loop(children).

{% for x in items %}…{% else %}…{% endfor %}
items sequence
what to iterate
if condition
loop only matching items
recursive flag
descend into nested items
template
{% for x in items %}{{ loop.index }}:{{ x }}{% if not loop.last %}, {% endif %}{% else %}none{% endfor %}
data
{"items":["a","b","c"]}
output
1:a, 2:b, 3:c

statement set

Bind a name to a value, or to a block of markup with endset.

{% set name = expr %} · {% set name %}…{% endset %}
name name
the variable
expr value
a value or filter chain
block flag
a block form with endset
template
{% set greeting %}Hello {{ name }}{% endset %}{{ greeting }}
data
{"name":"Ada"}
output
Hello Ada

statement with

Give names local values for the enclosed block.

{% with a = 1, b = 2 %}…{% endwith %}
names assignments
names and their values
template
{% with total = 3 %}{{ total }}{% endwith %}
output
3

Templates and reuse

statement macro

Define a reusable block with parameters; call it by name, or with a caller block via endcall.

{% macro name(args) %}…{% endmacro %} · {% call name(args) %}…{% endcall %}
args parameters
names, defaults, a rest parameter
template
{% macro field(n, v="") %}<input name="{{ n }}" value="{{ v }}">{% endmacro %}{{ field("q") }}
output
<input name="q" value="">

statement filter

Apply a filter to a block of markup.

{% filter upper %}…{% endfilter %}
filter filter
the filter and its arguments
template
{% filter upper %}hello {{ name }}{% endfilter %}
data
{"name":"ada"}
output
HELLO ADA

statement block

Define a named block a parent can fill; super() calls the parent's block, scoped sees the loop around it, required must be filled, append and prepend add to it. The indentation syntax has block append and block prepend too. Needs a loader through Env::new(load=…).

{% extends "base" %} · {% block name %}…{% endblock %}
template
{% extends "layout.html" %}
{% block body %}page{% endblock %}

Inheritance needs a loader, so the example below is shown, not run. The parent is read through load passed to Env::new; the Guide walks a full layout.

statement include

Pull in another template; ignore missing tolerates a missing file, with context shares the names, inline renders in place, raw includes plain text, and a block lands where the included file says yield. Needs a loader.

{% include "partial" %} · {% include "partial" ignore missing with context %}
missing flag
ignore a missing file
context flag
share local names
inline flag
render in place
raw flag
include as text
template
{% include "footer.html" ignore missing %}

Includes a named template through the loader, so the syntax is shown rather than run here.

statement import

Import names from another template as a module, or bring chosen names in directly; with context shares the names. Needs a loader.

{% import "ui" as ui %} · {% from "ui" import card %}
context flag
share local names
template
{% from "ui.html" import card %}{{ card("Title", "Note") }}

Reads the module through the loader, so the syntax is shown rather than run here.

Output and escaping

statement raw

Write text exactly as written, with no substitution.

{% raw %}…{% endraw %}
template
{% raw %}{{ not_evaluated }}{% endraw %}
output
{{ not_evaluated }}

statement autoescape

Turn escaping on or off for the enclosed block.

{% autoescape false %}…{% endautoescape %}
flag bool
escape or not
template
{% autoescape false %}{{ html }}{% endautoescape %}
data
{"html":"<b>"}
output
<b>

statement show

Write the block either way; when the condition is false it is hidden with an inline style, not removed.

{% show cond %}…{% endshow %}
cond bool
whether to show
template
{% show ok %}<b>shown</b>{% endshow %}
data
{"ok":true}
output
<b>shown</b>

statement debug

Print the current context: every name in scope.

{% debug %}
template
{% debug %}
output
{…all names in scope…}

Internationalisation

statement trans

Mark text for translation; pluralize switches on a count. With no translation seam the source text stands.

{% trans %}…{% endtrans %} · {% trans count=n %}…{% pluralize %}…{% endtrans %}
count number
the plural count
context string
a message context
template
{% trans count=n %}{{ count }} item{% pluralize %}{{ count }} items{% endtrans %}
data
{"n":3}
output
3 items

Side effects and caching

statement do

Evaluate an expression for its side effect, typically calling a method of a host object.

{% do object.method() %}
expr call
a callable to run
template
{% do user.log("visited") %}
output
(no output; runs the callable for its effect)

statement once

Render a block once and, with a cache passed to Env::new, keep it; without one it renders every time.

{% once key %}…{% endonce %}
key value
the cache key
template
{% once "sidebar" %}{{ 1 + 1 }}{% endonce %}
output
2