is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter:
{{ [1, 2, 3]|join('|') }}
-> 1|2|3
{{ [1, 2, 3]|join }}
-> 123
It is also possible to join certain attributes of an object:
{{ users|join(', ', attribute='username') }}
New in version 2.6: The attribute parameter was added.
Return the last item of a sequence.
Return the number of items of a sequence or mapping.
Aliases : | count |
---|
Convert the value into a list. If it was a string the returned list will be a list of characters.
Convert a value to lowercase.
Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list of users but you are only interested in a list of usernames:
Users on this page: {{ users|map(attribute='username')|join(', ') }}
Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good example would be applying a text conversion filter on a sequence:
Users on this page: {{ titles|map('lower')|join(', ') }}
New in version 2.7.
Pretty print a variable. Useful for debugging.
With Jinja 1.2 onwards you can pass it a parameter. If this parameter is truthy the output will be more verbose (this requires pretty)
Return a random item from the sequence.
Filters a sequence of objects by appying a test to either the object or the attribute and rejecting the ones with the test succeeding.
Example usage:
{{ numbers|reject("odd") }}
New in version 2.7.
Filters a sequence of objects by appying a test to either the object or the attribute and rejecting the ones with the test succeeding.
{{ users|rejectattr("is_active") }}
{{ users|rejectattr("email", "none") }}
New in version 2.7.
Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument count is given, only the first count occurrences are replaced:
{{ "Hello World"|replace("Hello", "Goodbye") }}
-> Goodbye World
{{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
-> d'oh, d'oh, aaargh
Reverse the object or return an iterator the iterates over it the other way round.
Round the number to a given precision. The first parameter specifies the precision (default is 0), the second the rounding method:
If you don’t specify a method 'common' is used.
{{ 42.55|round }}
-> 43.0
{{ 42.55|round(1, 'floor') }}
-> 42.5
Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through int:
{{ 42.55|round|int }}
-> 43
Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped.
Filters a sequence of objects by appying a test to either the object or the attribute and only selecting the ones with the test succeeding.
Example usage:
{{ numbers|select("odd") }}
New in version 2.7.
Filters a sequence of objects by appying a test to either the object or the attribute and only selecting the ones with the test succeeding.
Example usage:
{{ users|selectattr("is_active") }}
{{ users|selectattr("email", "none") }}
New in version 2.7.
Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns:
<div class="columwrapper">
{%- for column in items|slice(3) %}
<ul class="column-{{ loop.index }}">
{%- for item in column %}
<li>{{ item }}</li>
{%- endfor %}
</ul>
{%- endfor %}
</div>
If you pass it a second argument it’s used to fill missing values on the last iteration.
Sort an iterable. Per default it sorts ascending, if you pass it true as first argument it will reverse the sorting.
If the iterable is made of strings the third parameter can be used to control the case sensitiveness of the comparison which is disabled by default.
{% for item in iterable|sort %}
...
{% endfor %}
It is also possible to sort by an attribute (for example to sort by the date of an object) by specifying the attribute parameter:
{% for item in iterable|sort(attribute='date') %}
...
{% endfor %}
Changed in version 2.6: The attribute parameter was added.
Make a string unicode if it isn’t already. That way a markup string is not converted back to unicode.
Strip SGML/XML tags and replace adjacent whitespace by one space.
Returns the sum of a sequence of numbers plus the value of parameter ‘start’ (which defaults to 0). When the sequence is empty it returns start.
It is also possible to sum up only certain attributes:
Total: {{ items|sum(attribute='price') }}
Changed in version 2.6: The attribute parameter was added to allow suming up over attributes. Also the start parameter was moved on to the right.
Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.
Strip leading and trailing whitespace.
Return a truncated copy of the string. The length is specified with the first parameter which defaults to 255. If the second parameter is true the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign ("..."). If you want a different ellipsis sign than "..." you can specify it using the third parameter.
{{ "foo bar"|truncate(5) }}
-> "foo ..."
{{ "foo bar"|truncate(5, True) }}
-> "foo b..."
Convert a value to uppercase.
Escape strings for use in URLs (uses UTF-8 encoding). It accepts both dictionaries and regular strings as well as pairwise iterables.
New in version 2.7.
Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls “nofollow”:
{{ mytext|urlize(40, true) }}
links are shortened to 40 chars and defined with rel="nofollow"
Count the words in that string.
Return a copy of the string passed to the filter wrapped after 79 characters. You can override this default using the first parameter. If you set the second parameter to false Jinja will not split words apart if they are longer than width. By default, the newlines will be the default newlines for the environment, but this can be changed using the wrapstring keyword argument.
New in version 2.7: Added support for the wrapstring parameter.
Create an SGML/XML attribute string based on the items in a dict. All values that are neither none nor undefined are automatically escaped:
<ul{{ {'class': 'my_list', 'missing': none,
'id': 'list-%d'|format(variable)}|xmlattr }}>
...
</ul>
Results in something like this:
<ul class="my_list" id="list-42">
...
</ul>
As you can see it automatically prepends a space in front of the item if the filter returned something unless the second parameter is false.
Return whether the object is callable (i.e., some kind of function). Note that classes are callable, as are instances with a __call__() method.
Return true if the variable is defined:
{% if variable is defined %}
value of variable: {{ variable }}
{% else %}
variable is not defined
{% endif %}
See the default() filter for a simple way to set undefined variables.
Check if a variable is divisible by a number.
Check if the value is escaped.
Return true if the variable is even.
Check if it’s possible to iterate over an object.
Return true if the variable is lowercased.
Return true if the object is a mapping (dict etc.).
New in version 2.6.
Return true if the variable is none.
Return true if the variable is a number.
Return true if the variable is odd.
Check if an object points to the same memory address than another object:
{% if foo.attribute is sameas false %}
the foo attribute really is the `False` singleton
{% endif %}
Return true if the variable is a sequence. Sequences are variables that are iterable.
Return true if the object is a string.
Return true if the variable is uppercased.
The following functions are available in the global scope by default:
Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements.
This is useful to repeat a template block multiple times for example to fill a list. Imagine you have 7 users in the list but you want to render three empty items to enforce a height with CSS:
<ul>
{% for user in users %}
<li>{{ user.username }}</li>
{% endfor %}
{% for number in range(10 - users|count) %}
<li class="empty"><span>...</span></li>
{% endfor %}
</ul>
Generates some lorem ipsum for the template. Per default five paragraphs with HTML are generated each paragraph between 20 and 100 words. If html is disabled regular text is returned. This is useful to generate simple contents for layout testing.
A convenient alternative to dict literals. {'foo': 'bar'} is the same as dict(foo='bar').
The cycler allows you to cycle among values similar to how loop.cycle works. Unlike loop.cycle however you can use this cycler outside of loops or over multiple loops.
This is for example very useful if you want to show a list of folders and files, with the folders on top, but both in the same list with alternating row colors.
The following example shows how cycler can be used:
{% set row_class = cycler('odd', 'even') %}
<ul class="browser">
{% for folder in folders %}
<li class="folder {{ row_class.next() }}">{{ folder|e }}</li>
{% endfor %}
{% for filename in files %}
<li class="file {{ row_class.next() }}">{{ filename|e }}</li>
{% endfor %}
</ul>
A cycler has the following attributes and methods:
Resets the cycle to the first item.
Goes one item a head and returns the then current item.
Returns the current item.
new in Jinja 2.1
A tiny helper that can be use to “join” multiple sections. A joiner is passed a string and will return that string every time it’s called, except the first time in which situation it returns an empty string. You can use this to join things:
{% set pipe = joiner("|") %}
{% if categories %} {{ pipe() }}
Categories: {{ categories|join(", ") }}
{% endif %}
{% if author %} {{ pipe() }}
Author: {{ author() }}
{% endif %}
{% if can_edit %} {{ pipe() }}
<a href="?action=edit">Edit</a>
{% endif %}
new in Jinja 2.1
The following sections cover the built-in Jinja2 extensions that may be enabled by the application. The application could also provide further extensions not covered by this documentation. In that case there should be a separate document explaining the extensions.
If the i18n extension is enabled it’s possible to mark parts in the template as translatable. To mark a section as translatable you can use trans:
<p>{% trans %}Hello {{ user }}!{% endtrans %}</p>
To translate a template expression — say, using template filters or just accessing an attribute of an object — you need to bind the expression to a name for use within the translation block:
<p>{% trans user=user.username %}Hello {{ user }}!{% endtrans %}</p>
If you need to bind more than one expression inside a trans tag, separate the pieces with a comma (,):
{% trans book_title=book.title, author=author.name %}
This is {{ book_title }} by {{ author }}
{% endtrans %}
Inside trans tags no statements are allowed, only variable tags are.
To pluralize, specify both the singular and plural forms with the pluralize tag, which appears between trans and endtrans:
{% trans count=list|length %}
There is {{ count }} {{ name }} object.
{% pluralize %}
There are {{ count }} {{ name }} objects.
{% endtrans %}
Per default the first variable in a block is used to determine the correct singular or plural form. If that doesn’t work out you can specify the name which should be used for pluralizing by adding it as parameter to pluralize:
{% trans ..., user_count=users|length %}...
{% pluralize user_count %}...{% endtrans %}
It’s also possible to translate strings in expressions. For that purpose three functions exist:
_ gettext: translate a single string - ngettext: translate a pluralizable string - _: alias for gettext
For example you can print a translated string easily this way:
{{ _('Hello World!') }}
To use placeholders you can use the format filter:
{{ _('Hello %(user)s!')|format(user=user.username) }}
For multiple placeholders always use keyword arguments to format as other languages may not use the words in the same order.
Changed in version 2.5.
If newstyle gettext calls are activated (Newstyle Gettext), using placeholders is a lot easier:
{{ gettext('Hello World!') }}
{{ gettext('Hello %(name)s!', name='World') }}
{{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}
Note that the ngettext function’s format string automatically receives the count as num parameter additionally to the regular parameters.
If the expression-statement extension is loaded a tag called do is available that works exactly like the regular variable expression ({{ ... }}) just that it doesn’t print anything. This can be used to modify lists:
{% do navigation.append('a string') %}
If the application enables the Loop Controls it’s possible to use break and continue in loops. When break is reached, the loop is terminated; if continue is reached, the processing is stopped and continues with the next iteration.
Here a loop that skips every second item:
{% for user in users %}
{%- if loop.index is even %}{% continue %}{% endif %}
...
{% endfor %}
Likewise a look that stops processing after the 10th iteration:
{% for user in users %}
{%- if loop.index >= 10 %}{% break %}{% endif %}
{%- endfor %}
New in version 2.3.
If the application enables the With Statement it is possible to use the with keyword in templates. This makes it possible to create a new inner scope. Variables set within this scope are not visible outside of the scope.
With in a nutshell:
{% with %}
{% set foo = 42 %}
{{ foo }} foo is 42 here
{% endwith %}
foo is not visible here any longer
Because it is common to set variables at the beginning of the scope you can do that within the with statement. The following two examples are equivalent:
{% with foo = 42 %}
{{ foo }}
{% endwith %}
{% with %}
{% set foo = 42 %}
{{ foo }}
{% endwith %}
New in version 2.4.
If the application enables the Autoescape Extension one can activate and deactivate the autoescaping from within the templates.
Example:
{% autoescape true %}
Autoescaping is active within this block
{% endautoescape %}
{% autoescape false %}
Autoescaping is inactive within this block
{% endautoescape %}
After the endautoescape the behavior is reverted to what it was before.