List of Builtin Filters

abs()float()lower()round()tojson()
attr()forceescape()map()safe()trim()
batch()format()max()select()truncate()
capitalize()groupby()min()selectattr()unique()
center()indent()pprint()slice()upper()
default()int()random()sort()urlencode()
dictsort()join()reject()string()urlize()
escape()last()rejectattr()striptags()wordcount()
filesizeformat()length()replace()sum()wordwrap()
first()list()reverse()title()xmlattr()
  • abs(x, /)
  • Return the absolute value of the argument.
  • attr(obj, name)
  • Get an attribute of an object. foo|attr("bar") works likefoo.bar just that always an attribute is returned and items are notlooked up.

See Notes on subscriptions for more details.

  • batch(value, linecount, fill_with=None)
  • A filter that batches items. It works pretty much like _slice_just the other way round. It returns a list of lists with thegiven number of items. If you provide a second parameter thisis used to fill up missing items. See this example:
  1. <table>
  2. {%- for row in items|batch(3, '&nbsp;') %}
  3. <tr>
  4. {%- for column in row %}
  5. <td>{{ column }}</td>
  6. {%- endfor %}
  7. </tr>
  8. {%- endfor %}
  9. </table>
  • capitalize(s)
  • Capitalize a value. The first character will be uppercase, all otherslowercase.
  • center(value, width=80)
  • Centers the value in a field of a given width.
  • default(value, default_value='', boolean=False)
  • If the value is undefined it will return the passed default value,otherwise the value of the variable:
  1. {{ my_variable|default('my_variable is not defined') }}

This will output the value of myvariable if the variable wasdefined, otherwise 'my_variable is not defined'. If you wantto use default with variables that evaluate to false you have toset the second parameter to _true:

  1. {{ ''|default('the string was empty', true) }}
  • Aliases
  • d
  • dictsort(value, case_sensitive=False, by='key', reverse=False)
  • Sort a dict and yield (key, value) pairs. Because python dicts areunsorted you may want to use this function to order them by eitherkey or value:
  1. {% for item in mydict|dictsort %}
  2. sort the dict by key, case insensitive
  3. {% for item in mydict|dictsort(reverse=true) %}
  4. sort the dict by key, case insensitive, reverse order
  5. {% for item in mydict|dictsort(true) %}
  6. sort the dict by key, case sensitive
  7. {% for item in mydict|dictsort(false, 'value') %}
  8. sort the dict by value, case insensitive
  • escape(s)
  • Convert the characters &, <, >, ‘, and ” in string s to HTML-safesequences. Use this if you need to display text that might containsuch characters in HTML. Marks return value as markup string.

    • Aliases
    • e
  • filesizeformat(value, binary=False)
  • Format 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 binaryprefixes are used (Mebi, Gibi).
  • first(seq)
  • Return the first item of a sequence.
  • float(value, default=0.0)
  • Convert the value into a floating point number. If theconversion doesn’t work it will return 0.0. You canoverride this default using the first parameter.
  • forceescape(value)
  • Enforce HTML escaping. This will probably double escape variables.
  • format(value, *args, **kwargs)
  • Apply python string formatting on an object:
  1. {{ "%s - %s"|format("Hello?", "Foo!") }}
  2. -> Hello? - Foo!
  • groupby(value, attribute)
  • Group a sequence of objects by a common attribute.

If you for example have a list of dicts or objects that represent personswith gender, first_name and last_name attributes and you want togroup all users by genders you can do something like the followingsnippet:

  1. <ul>
  2. {% for group in persons|groupby('gender') %}
  3. <li>{{ group.grouper }}<ul>
  4. {% for person in group.list %}
  5. <li>{{ person.first_name }} {{ person.last_name }}</li>
  6. {% endfor %}</ul></li>
  7. {% endfor %}
  8. </ul>

Additionally it’s possible to use tuple unpacking for the grouper andlist:

  1. <ul>
  2. {% for grouper, list in persons|groupby('gender') %}
  3. ...
  4. {% endfor %}
  5. </ul>

As you can see the item we’re grouping by is stored in the grouper_attribute and the _list contains all the objects that have this grouperin common.

Changelog

Changed in version 2.6: It’s now possible to use dotted notation to group by the childattribute of another attribute.

  • indent(s, width=4, first=False, blank=False, indentfirst=None)
  • Return a copy of the string with each line indented by 4 spaces. Thefirst line and blank lines are not indented by default.

    • Parameters
      • width – Number of spaces to indent by.

      • first – Don’t skip indenting the first line.

      • blank – Don’t skip indenting empty lines.

Changed in version 2.10: Blank lines are not indented by default.

Rename the indentfirst argument to first.

  • int(value, default=0, base=10)
  • Convert the value into an integer. If theconversion doesn’t work it will return 0. You canoverride this default using the first parameter. Youcan also override the default base (10) in the secondparameter, which handles input with prefixes such as0b, 0o and 0x for bases 2, 8 and 16 respectively.The base is ignored for decimal numbers and non-string values.
  • join(value, d='', attribute=None)
  • Return a string which is the concatenation of the strings in thesequence. The separator between elements is an empty string perdefault, you can define it with the optional parameter:
  1. {{ [1, 2, 3]|join('|') }}
  2. -> 1|2|3
  3. {{ [1, 2, 3]|join }}
  4. -> 123

It is also possible to join certain attributes of an object:

  1. {{ users|join(', ', attribute='username') }}

Changelog

New in version 2.6: The attribute parameter was added.

  • last(seq)
  • Return the last item of a sequence.
  • length(obj, /)
  • Return the number of items in a container.

    • Aliases
    • count
  • list(value)
  • Convert the value into a list. If it was a string the returned listwill be a list of characters.
  • lower(s)
  • Convert a value to lowercase.
  • map(*args, **kwargs)
  • 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 reallyonly interested in a certain value of it.

The basic usage is mapping on an attribute. Imagine you have a listof users but you are only interested in a list of usernames:

  1. Users on this page: {{ users|map(attribute='username')|join(', ') }}

Alternatively you can let it invoke a filter by passing the name of thefilter and the arguments afterwards. A good example would be applying atext conversion filter on a sequence:

  1. Users on this page: {{ titles|map('lower')|join(', ') }}

Changelog

New in version 2.7.

  • max(value, case_sensitive=False, attribute=None)
  • Return the largest item from the sequence.
  1. {{ [1, 2, 3]|max }}
  2. -> 3
  • Parameters
    • case_sensitive – Treat upper and lower case strings as distinct.

    • attribute – Get the object with the max value of this attribute.

  • min(value, case_sensitive=False, attribute=None)
  • Return the smallest item from the sequence.
  1. {{ [1, 2, 3]|min }}
  2. -> 1
  • Parameters
    • case_sensitive – Treat upper and lower case strings as distinct.

    • attribute – Get the object with the max value of this attribute.

  • pprint(value, verbose=False)
  • Pretty print a variable. Useful for debugging.

With Jinja 1.2 onwards you can pass it a parameter. If this parameteris truthy the output will be more verbose (this requires pretty)

  • random(seq)
  • Return a random item from the sequence.
  • reject(*args, **kwargs)
  • 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 usage:

  1. {{ numbers|reject("odd") }}

Changelog

New in version 2.7.

  • rejectattr(*args, **kwargs)
  • Filters a sequence of objects by applying a test to the specifiedattribute of each object, and rejecting the objects with the testsucceeding.

If no test is specified, the attribute’s value will be evaluated asa boolean.

  1. {{ users|rejectattr("is_active") }}
  2. {{ users|rejectattr("email", "none") }}

Changelog

New in version 2.7.

  • replace(s, old, new, count=None)
  • Return a copy of the value with all occurrences of a substringreplaced with a new one. The first argument is the substringthat should be replaced, the second is the replacement string.If the optional third argument count is given, only the firstcount occurrences are replaced:
  1. {{ "Hello World"|replace("Hello", "Goodbye") }}
  2. -> Goodbye World
  3. {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
  4. -> d'oh, d'oh, aaargh
  • reverse(value)
  • Reverse the object or return an iterator that iterates over it the otherway round.
  • round(value, precision=0, method='common')
  • Round the number to a given precision. The firstparameter specifies the precision (default is 0), thesecond the rounding method:

    • 'common' rounds either up or down

    • 'ceil' always rounds up

    • 'floor' always rounds down

If you don’t specify a method 'common' is used.

  1. {{ 42.55|round }}
  2. -> 43.0
  3. {{ 42.55|round(1, 'floor') }}
  4. -> 42.5

Note that even if rounded to 0 precision, a float is returned. Ifyou need a real integer, pipe it through int:

  1. {{ 42.55|round|int }}
  2. -> 43
  • safe(value)
  • Mark the value as safe which means that in an environment with automaticescaping enabled this variable will not be escaped.
  • select(*args, **kwargs)
  • 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 usage:

  1. {{ numbers|select("odd") }}
  2. {{ numbers|select("odd") }}
  3. {{ numbers|select("divisibleby", 3) }}
  4. {{ numbers|select("lessthan", 42) }}
  5. {{ strings|select("equalto", "mystring") }}

Changelog

New in version 2.7.

  • selectattr(*args, **kwargs)
  • Filters a sequence of objects by applying a test to the specifiedattribute of each object, and only selecting the objects with thetest succeeding.

If no test is specified, the attribute’s value will be evaluated asa boolean.

Example usage:

  1. {{ users|selectattr("is_active") }}
  2. {{ users|selectattr("email", "none") }}

Changelog

New in version 2.7.

  • slice(value, slices, fill_with=None)
  • Slice an iterator and return a list of lists containingthose items. Useful if you want to create a div containingthree ul tags that represent columns:
  1. <div class="columwrapper">
  2. {%- for column in items|slice(3) %}
  3. <ul class="column-{{ loop.index }}">
  4. {%- for item in column %}
  5. <li>{{ item }}</li>
  6. {%- endfor %}
  7. </ul>
  8. {%- endfor %}
  9. </div>

If you pass it a second argument it’s used to fill missingvalues on the last iteration.

  • sort(value, reverse=False, case_sensitive=False, attribute=None)
  • Sort an iterable. Per default it sorts ascending, if you pass ittrue as first argument it will reverse the sorting.

If the iterable is made of strings the third parameter can be used tocontrol the case sensitiveness of the comparison which is disabled bydefault.

{% for item in iterable|sort %}
    ...
{% endfor %}

It is also possible to sort by an attribute (for example to sortby the date of an object) by specifying the attribute parameter:

{% for item in iterable|sort(attribute='date') %}
    ...
{% endfor %}

Changelog

Changed in version 2.6: The attribute parameter was added.

  • string(object)
  • Make a string unicode if it isn’t already. That way a markupstring is not converted back to unicode.
  • striptags(value)
  • Strip SGML/XML tags and replace adjacent whitespace by one space.
  • sum(iterable, attribute=None, start=0)
  • Returns the sum of a sequence of numbers plus the value of parameter‘start’ (which defaults to 0). When the sequence is empty it returnsstart.

It is also possible to sum up only certain attributes:

Total: {{ items|sum(attribute='price') }}

Changelog

Changed in version 2.6: The attribute parameter was added to allow suming up overattributes. Also the start parameter was moved on to the right.

  • title(s)
  • Return a titlecased version of the value. I.e. words will start withuppercase letters, all remaining characters are lowercase.
  • tojson(value, indent=None)
  • Dumps a structure to JSON so that it’s safe to use in <script>tags. It accepts the same arguments and returns a JSON string. Note thatthis is available in templates through the |tojson filter which willalso mark the result as safe. Due to how this function escapes certaincharacters this is safe even if used outside of <script> tags.

The following characters are escaped in strings:

  • <

  • >

  • &

  • '

This makes it safe to embed such strings in any place in HTML with thenotable exception of double quoted attributes. In that case singlequote your attributes or HTML escape it in addition.

The indent parameter can be used to enable pretty printing. Set it tothe number of spaces that the structures should be indented with.

Note that this filter is for use in HTML contexts only.

Changelog

New in version 2.9.

  • trim(value)
  • Strip leading and trailing whitespace.
  • truncate(s, length=255, killwords=False, end='…', leeway=None)
  • Return a truncated copy of the string. The length is specifiedwith the first parameter which defaults to 255. If the secondparameter is true the filter will cut the text at length. Otherwiseit will discard the last word. If the text was in facttruncated it will append an ellipsis sign ("…"). If you want adifferent ellipsis sign than "…" you can specify it using thethird parameter. Strings that only exceed the length by the tolerancemargin given in the fourth parameter will not be truncated.
{{ "foo bar baz qux"|truncate(9) }}
    -> "foo..."
{{ "foo bar baz qux"|truncate(9, True) }}
    -> "foo ba..."
{{ "foo bar baz qux"|truncate(11) }}
    -> "foo bar baz qux"
{{ "foo bar baz qux"|truncate(11, False, '...', 0) }}
    -> "foo bar..."

The default leeway on newer Jinja2 versions is 5 and was 0 before butcan be reconfigured globally.

  • unique(value, case_sensitive=False, attribute=None)
  • Returns a list of unique items from the the given iterable.
{{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}
    -> ['foo', 'bar', 'foobar']

The unique items are yielded in the same order as their first occurrence inthe iterable passed to the filter.

  • Parameters
    • case_sensitive – Treat upper and lower case strings as distinct.

    • attribute – Filter objects with unique values for this attribute.

  • upper(s)
  • Convert a value to uppercase.
  • urlencode(value)
  • Escape strings for use in URLs (uses UTF-8 encoding). It accepts bothdictionaries and regular strings as well as pairwise iterables.

Changelog

New in version 2.7.

  • urlize(value, trim_url_limit=None, nofollow=False, target=None, rel=None)
  • Converts URLs in plain text into clickable links.

If you pass the filter an additional integer it will shorten the urlsto 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"

If target is specified, the target attribute will be added to the<a> tag:

{{ mytext|urlize(40, target='_blank') }}

Changelog

Changed in version 2.8+: The target parameter was added.

  • wordcount(s)
  • Count the words in that string.
  • wordwrap(s, width=79, break_long_words=True, wrapstring=None)
  • Return a copy of the string passed to the filter wrapped after79 characters. You can override this default using the firstparameter. If you set the second parameter to false Jinja will notsplit words apart if they are longer than width. By default, the newlineswill be the default newlines for the environment, but this can be changedusing the wrapstring keyword argument.

Changelog

New in version 2.7: Added support for the wrapstring parameter.

  • xmlattr(d, autospace=True)
  • Create an SGML/XML attribute string based on the items in a dict.All values that are neither none nor undefined are automaticallyescaped:
<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 itemif the filter returned something unless the second parameter is false.