Filters
14 minute read
Filters appear inside {{ ... }} tags and are separated from the variable by a pipe symbol (|). Filters may have optional arguments in parentheses.
Multiple filters can be chained; the output of one filter is applied to the next.
{# Example 1 #}
{% set foo = ["hello", "world"] %}
{{ foo | first | upper }}
{# Example 2 #}
{# You can also apply filters on a block of template data within the filter section #}
{% filter upper %}
hello world
{% endfilter %}
Result:
{# Example 1 #}
HELLO
{# Example 2 #}
HELLO WORLD
abs
Filter returns the absolute (non-negative) value of the argument.
Example:
{% set foo = -5 %}
{{ foo | abs }}
Result:
5
See also: float, int, max, min, round, sum.
attr
Filter returns the attribute of an object.
foo | attr("bar") works like foo.bar but will always return an attribute and items are not looked up.
The filter only attempts to look up an attribute and not an item (for example, if foo is a dictionary and bar is a key item, it will not be found).
Example:
{{ foo | attr("bar") }}
See also: groupby, map, reject, rejectattr, select, selectattr.
batch
Filter that batches items.
It works similar to slice except that it returns a list of lists with the given number of items.
Provide a second parameter to fill in missing items.
Example:
{# batch(linecount, fill_with=None) #}
{% set items = ["Dev", "Prod"] %}
{%- for item in items | batch(3, 'Test') %}
{%- for env in item %}
{{ env }}
{%- endfor %}
{%- endfor %}
Result:
Dev
Prod
Test
See also: first, join, last, length, list, slice, sort.
capitalize
Filter capitalizes a value.
The first character will be uppercase, all others lowercase.
Example:
{% set foo = "hello world" %}
{{ foo | capitalize }}
Result:
Hello world
See also: lower, title, upper.
center
Filter centers the value in a field of a given width.
Example:
{# center(width) #}
{% set foo = "hello world" %}
{{ foo | center(80) }}
Result:
hello world
default
Filter returns the passed default value if the value is undefined. Otherwise, if the variable has a value, the value of the variable is returned.
Example:
{# default(default_value='', boolean=False) #}
{% set foo = "" %}
{{ foo | default("hello world", true) }}
Result:
hello world
See also: required.
dictsort
Filter sorts a python dict and yield (key, value) pairs.
Order by either key or value.
Example:
{# dictsort(case_sensitive=False, by='key', reverse=False) #}
{# sort by key: case insensitive #}
{% for item in items | dictsort %}
{# sort by key: case insensitive and in reverse order #}
{% for item in items | dictsort(reverse=true) %}
{# sort by key: case sensitive #}
{% for item in items | dictsort(true) %}
{# sort by value: case insensitive #}
{% for item in items | dictsort(false, 'value') %}
See also: sort.
escape
Filter converts the characters &, <, >, ', and " in strings to HTML-safe sequences.
Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.
Example:
{% set foo = "&" %}
{{ foo | escape }}
Result:
&
See also: forceescape, safe.
filesizeformat
Filter formats the value like a ‘human-readable’ file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc).
Per default decimal prefixes are used (Mega, Giga, etc.), if the second parameter is set to True the binary prefixes are used (Mebi, Gibi).
Example:
{# filesizeformat(binary=False) #}
{{ myfile | filesizeformat }}
first
Filter returns the first item of a sequence.
Example:
{% set items = ["Dev", "Prod"] %}
{{ items | first }}
Result:
Dev
See also: batch, join, last, length, list, slice, sort, unique.
float
Filter converts the value into a floating point number.
If the conversion does not work, it will return 0.0.
You can override this default using the first parameter.
Example:
{# float(default=0.0) #}
{% set foo = 1 %}
{{ foo | float }}
Result:
1.0
See also: abs, int, max, min, round, sum.
forceescape
Enforce HTML escaping. This will double escape variables.
Example:
{% set foo = "&" %}
{{ foo | forceescape }}
Result:
&
format
Filter applies the given values to a printf-style format string, like string % values.
Example:
{# format(*args, **kwargs) #}
{% set foo = "Hello" %}
{% set bar = "World" %}
{{ "%s, %s!" | format(foo, bar) }}
Result:
Hello, World!
groupby
Filter groups a sequence of objects by an attribute.
The attribute can use dot notation for nested access, like foo.bar.
The values are sorted first and only one group is returned for each unique value.
Example:
{# groupby(attribute) #}
{#
For example, a list of User objects with a city attribute can be rendered in groups.
In this example, grouper refers to the city value of the group.
#}
{% for city, items in users | groupby("city") %}
{{ city }}
{% for user in items %}
- {{ user.name }}
{% endfor %}
{% endfor %}
See also: attr, map, reject, rejectattr, select, selectattr.
indent
Filter returns a copy of the string with each line indented by 4 spaces.
The first line and blank lines are not indented by default.
Example:
{# indent(width=4, first=False, blank=False, indentfirst=None) #}
{% set foo = "hello world" %}
{{ foo | indent(2, true) }}
Result:
hello world
int
Filter converts the value into an integer.
If the conversion does not work, it will return 0.
Example:
{# int(default=0, base=10) #}
{% set foo = "1" %}
{{ foo | int }}
Result:
1
See also: abs, float, max, min, round, sum.
join
Filter returns a string which is the concatenation of the strings in the sequence.
The separator between elements is an empty string per default.
Example:
{# join(separator='', attribute=None) #}
{% set foo = ["Dev", "Prod"] %}
{{ foo | join(", ") }}
Result:
Dev, Prod
See also: batch, first, last, length, list, slice, sort.
last
Filter returns the last item of a sequence.
Example:
{% set foo = ["Dev", "Prod"] %}
{{ foo | last }}
Result:
Prod
See also: batch, first, join, length, list, slice, sort, unique.
length
Filter returns the number of items in a container.
Example:
{% set foo = ["Dev", "Prod"] %}
{{ foo | length }}
Result:
2
See also: batch, first, join, last, list, slice, sort, wordcount.
list
Filter converts the value into a list.
If it is a string, the returned list will be a list of characters.
Example:
{% set foo = "Dev" %}
{{ foo | list }}
Result:
['D', 'e', 'v']
See also: batch, first, join, last, length, slice, sort.
lower
Filter converts a value to lowercase.
Example:
{% set foo = "Hello World" %}
{{ foo | lower }}
Result:
hello world
See also: capitalize, title, upper.
map
Filter 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.
Example:
{# map(*args, **kwargs) #}
{#
Imagine you have a list of users
but you are only interested in a list of usernames
#}
{{ users | map(attribute="username") | join(", ") }}
{#
You can specify a default value to use if an object in the list
does not have the given attribute.
#}
{{ users | map(attribute="username", default="Anonymous") | 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.
#}
{{ titles | map("lower") | join(", ") }}
See also: attr, groupby, reject, rejectattr, select, selectattr.
max
Filter returns the largest item from the sequence.
Example:
{# max(case_sensitive=False, attribute=None) #}
{% set foo = [1, 2, 3] %}
{{ foo | max }}
Result:
3
See also: abs, float, int, min, round, sum.
min
Filter returns the smallest item from the sequence.
Example:
{# min(case_sensitive=False, attribute=None) #}
{% set foo = [1, 2, 3] %}
{{ foo | min }}
Result:
1
See also: abs, float, int, max, round, sum.
pprint
Filter pretty prints a variable. Useful for debugging.
Example:
{# pprint(verbose=False) #}
{{ foo | pprint }}
random
Filter returns a random item from the sequence.
Example:
{% set foo = [1, 3, 5, 7, 9] %}
{{ foo | random }}
Result:
7
random_mac
Filter returns a random MAC Address.
When the variable is defined, the variable value will return instead of a random generated MAC Address.
Example:
{% set foo = '' %}
{{ foo | random_mac }}
Result:
02:99:5b:a4:47:7c
reject
Filters a sequence of objects by applying a test to each object, and rejecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
Example:
{{ numbers | reject("odd") }}
See also: attr, groupby, map, rejectattr, select, selectattr.
rejectattr
Filters a sequence of objects by applying a test to the specified attribute of each object, and rejecting the objects with the test succeeding.
If no test is specified, the attribute’s value will be evaluated as a boolean.
Example:
{{ users | rejectattr("is_active") }}
{{ users | rejectattr("email", "none") }}
See also: attr, groupby, map, reject, select, selectattr.
replace
Filter returns a copy of the value with all occurrences of a substring replaced with a new one.
If the optional third argument count is given, only the first count occurrences are replaced.
Example:
{# replace(old, new, count=None) #}
{# Example 1 #}
{% set foo = "hello world" %}
{{ foo | replace("hello", "hi") }}
{# Example 2 #}
{% set bar = "aaa" %}
{{ bar | replace("a", "b", 2) }}
Result:
{# Example 1 #}
hi world
{# Example 2 #}
bba
required
Filter returns an error when a rendered variable results to empty (undefined or null).
Example:
{# required(message="NO MESSAGE DEFINED") #}
{% set foo = "" %}
{{ foo | required("foo was not defined") }}
Result:
ERROR: foo was not defined
See also: default.
reverse
Filter reverses the object or return an iterator that iterates over it the other way round.
Example:
{% set foo = ["Dev", "Prod"] %}
{{ foo | reverse | list }}
Result:
['Prod', 'Dev']
See also: sort.
round
Filter rounds the number to a given precision.
Example:
{# round(precision=0, method='common') #}
{#
-- METHODS --
common: rounds either up or down and is the default.
ceil: always rounds up.
floor: always rounds down.
#}
{% set foo = 1.65 %}
{# Method: common #}
{{ foo | round }}
{# Method: floor #}
{{ foo | round(1, "floor") }}
{# Method: ceil #}
{{ foo | round(1, "ceil") }}
Result:
{# Method: common #}
2.0
{# Method: floor #}
1.6
{# Method: ceil #}
1.7
See also: abs, float, int, max, min, sum.
safe
Filter marks the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped.
Example:
{% set foo = "&" %}
{{ foo | safe }}
Result:
&
See also: escape, forceescape.
select
Filters a sequence of objects by applying a test to each object, and only selecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
Example:
{# select(*args, **kwargs) #}
{{ numbers | select("odd") }}
{{ numbers | select("divisibleby", 3) }}
{{ numbers | select("lessthan", 42) }}
{{ strings | select("equalto", "mystring") }}
See also: attr, groupby, map, reject, rejectattr, selectattr.
selectattr
Filters a sequence of objects by applying a test to the specified attribute of each object, and only selecting the objects with the test succeeding.
If no test is specified, the attribute’s value will be evaluated as a boolean.
Example:
{# selectattr(*args, **kwargs) #}
{{ users | selectattr("is_active") }}
{{ users | selectattr("email", "none") }}
See also: attr, groupby, map, reject, rejectattr, select.
slice
Filter slices an iterator and return a list of lists containing those items.
Example:
{# slice(slices, fill_with=None) #}
{% set foo = ["Dev", "Prod"] %}
{{ foo | slice(3, "Test") | list }}
Result:
[['Dev'], ['Prod'], ['Test']]
See also: batch, first, join, last, length, list, sort.
sort
Filter sorts an iterable.
Example:
{# sort(reverse=False, case_sensitive=False, attribute=None) #}
{#
reverse: set to true to sort descending.
case_sensitive: set to true to sort upper and lower case strings separately.
attribute: when sorting objects or dicts, an attribute or key to sort by.
#}
{% set foo = ["Prod", "Dev"] %}
{{ foo | sort }}
Result:
['Dev', 'Prod']
See also: batch, dictsort, first, join, last, length, list, reverse, slice.
split
Filter splits a string value and returns the result value(s) in an array.
Example:
{# split(delimiter='') #}
{% set foo = "hostname.domain.com" %}
{# Example 1 #}
{{ foo.split('.') }}
{# Example 2 #}
{{ foo.split('.') | first }}
Result:
{# Example 1 #}
['hostname', 'domain', 'com']
{# Example 2 #}
hostname
See also: batch, dictsort, first, join, last, length, list, reverse, slice.
string
Filter makes a string unicode if it is not already.
That way a markup string is not converted back to unicode.
Example:
{{ object | string }}
striptags
Filter strips SGML/XML tags and replace adjacent whitespace by one space.
Example:
{{ xml | striptags }}
substring
Filter returns the substring.
Example:
{% set foo = "hostname" %}
{{ foo[0:4] }}
Result:
host
sum
Filter 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.
Example:
{# sum(attribute=None, start=0) #}
{% set foo = [1, 2] %}
{{ foo | sum }}
Result:
3
See also: abs, float, int, max, min, round.
title
Filter returns a title-cased version of the value.
Words will start with uppercase letters, all remaining characters are lowercase.
Example:
{% set foo = "hello world" %}
{{ foo | title }}
Result:
Hello World
See also: capitalize, lower, upper.
trim
Filter strips leading and trailing characters, by default whitespace.
Example:
{# trim(chars=None) #}
{% set foo = " hello world " %}
{{ foo | trim }}
Result:
hello world
truncate
Filter returns 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.
Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated.
Example:
{# truncate(length=255, killwords=False, end='...', leeway=None) #}
{# Example 1 #}
{{ "foo bar baz qux" | truncate(9) }}
{# Example 2 #}
{{ "foo bar baz qux" | truncate(9, True) }}
{# Example 3 #}
{{ "foo bar baz qux" | truncate(11) }}
{# Example 4 #}
{{ "foo bar baz qux" | truncate(11, False, '(...)', 0) }}
Result:
{# Example 1 #}
foo...
{# Example 2 #}
foo ba...
{# Example 3 #}
foo bar baz qux
{# Example 4 #}
foo bar(...)
unique
Filter returns a list of unique items from the given iterable.
Example:
{# unique(case_sensitive=False, attribute=None) #}
{% set foo = ["A", "A", "B", "A", "a", "b", "c", "b"] %}
{# Example 1 #}
{% for item in foo | unique %}
{{ item }}
{% endfor %}
{# Example 2 #}
{{ foo | unique(true) | list }}
Result:
{# Example 1 #}
A
B
c
{# Example 2 #}
['A', 'B', 'a', 'b', 'c']
upper
Filter converts a value to uppercase.
Example:
{% set foo = "hello world" %}
{{ foo | upper }}
Result:
HELLO WORLD
See also: capitalize, lower, title.
urlencode
Filter quotes data for use in a URL path or query using UTF-8.
Example:
{% set foo = "https://onefuse.example.com:443" %}
{{ foo | urlencode }}
Result:
https%3A//onefuse.example.com%3A443
See also: urlize.
urlize
Filter converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls to that number.
A third argument exists that makes the urls “nofollow”.
Example:
{# Link is shortened to 40 characters and defined with rel="nofollow" #}
{{ foo | urlize(40, true) }}
{# Link has target="_blank" attribute and will open in a new tab #}
{{ foo | urlize(target='_blank') }}
See also: urlencode.
wordcount
Filter counts the words in that string.
Example:
{% set foo = "hello world" %}
{{ foo | wordcount }}
Result:
2
See also: length.
wordwrap
Filter wraps a string to the given width.
Existing newlines are treated as paragraphs to be wrapped separately.
Example:
{# wordwrap(width, break_long_words=True, wrapstring=None, break_on_hyphens=True) #}
{#
width: Maximum length of wrapped lines.
break_long_words: If a word is longer than width, break it across lines.
break_on_hyphens: If a word contains hyphens, it may be split across lines.
wrapstring: String to join each wrapped line.
#}
{{ foo | wordwrap(80, break_long_words=false) }}