Filters, Tests and Helper Functions — Jinja Documentation

# Jinja

## Filters, Tests and Helper Functions

This part of the documentation lists the filter-, test- and helper functions you can use in templates.

## Filters

In the examples above you might have noticed the pipe symbols. Pipe symbols tell the engine that it has to apply a filter on the variable. Here is a small example:

    {{ variable|replace('foo', 'bar')|escape }}

If you want, you can also put whitespace between the filters.

This will look for a variable variable, pass it to the filter replace with the arguments `'foo'` and `'bar'`, and pass the result to the filter escape that automatically XML-escapes the value. The e filter is an alias for escape. Here is the complete list of supported filters:

abs

  Return the absolute value of a number.

  new in Jinja 1.1

batch

  A filter that batches items. It works pretty much like slice just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill missing items. See this example:

      <table>
      {%- for row in items|batch(3, '&nbsp;') %}
        <tr>
        {%- for column in row %}
          <tr>{{ column }}</td>
        {%- endfor %}
        </tr>
      {%- endfor %}
      </table>

  new in Jinja 1.1

capitalize
  Capitalize a value. The first character will be uppercase, all others lowercase.
capture

  Store the value in a variable called `captured` or a variable with the name provided. Useful for filter blocks:

      {% filter capture('foo') %}
          ...
      {% endfilter %}
      {{ foo }}

  This will output "..." two times. One time from the filter block and one time from the variable. If you don't want the filter to output something you can use it in clean mode:

      {% filter capture('foo', True) %}
          ...
      {% endfilter %}
      {{ foo }}

center
  Centers the value in a field of a given width.
default

  If the value is undefined it will return the passed default value, otherwise the value of the variable:

      {{ my_variable|default('my_variable is not defined') }}

  This will output the value of `my_variable` if the variable was defined, otherwise `'my_variable is not defined'`. If you want to use default with variables that evaluate to false you have to set the second parameter to true:

      {{ ''|default('the string was empty', true) }}

dformat

  Apply python mapping string formatting on an object:

      {{ "Hello %(username)s!"|dformat({'username': 'John Doe'}) }}
          -> Hello John Doe!

  This is useful when adding variables to translateable string expressions.

  New in Jinja 1.1

dictsort

  Sort a dict and yield (key, value) pairs. Because python dicts are unsorted you may want to use this function to order them by either key or value:

      {% for item in mydict|dictsort %}
          sort the dict by key, case insensitive

      {% for item in mydict|dicsort(true) %}
          sort the dict by key, case sensitive

      {% for item in mydict|dictsort(false, 'value') %}
          sort the dict by key, case insensitive, sorted
          normally and ordered by value.

escape

  XML escape `&`, `<`, and `>` in a string of data. If the optional parameter is true this filter will also convert `"` to `&quot;`. This filter is just used if the environment was configured with disabled auto_escape.

  This method will have no effect it the value is already escaped.

  Aliases: | e

filesizeformat
  Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc).
first
  Return the frist item of a sequence.
float
  Convert the value into a floating point number. If the conversion doesn't work it will return `0.0`. You can override this default using the first parameter.
format

  Apply python string formatting on an object:

      {{ "%s - %s"|format("Hello?", "Foo!") }}
          -> Hello? - Foo!

  Note that you cannot use the mapping syntax (`%(name)s`) like in python. Use |dformat for that.

getattribute

  Get one attribute from an object. Normally you don't have to use this filter because the attribute and subscript expressions try to either get an attribute of an object or an item. In some situations it could be that there is an item and an attribute with the same name. In that situation only the item is returned, never the attribute.

      {{ foo.bar }} -> {{ foo|getattribute('bar') }}

  New in Jinja 1.2

getitem

  This filter basically works like the normal subscript expression but it doesn't fall back to attribute lookup. If an item does not exist for an object undefined is returned.

      {{ foo.bar }} -> {{ foo|getitem('bar') }}

  New in Jinja 1.2

groupby

  Group a sequence of objects by a common attribute.

  If you for example have a list of dicts or objects that represent persons with gender, first_name and last_name attributes and you want to group all users by genders you can do something like the following snippet:

      <ul>
      {% for group in persons|groupby('gender') %}
          <li>{{ group.grouper }}<ul>
          {% for person in group.list %}
              <li>{{ person.first_name }} {{ person.last_name }}</li>
          {% endfor %}</ul></li>
      {% endfor %}
      </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 grouper in common.

  New in Jinja 1.2

indent

  {{ s|indent[ width[ indentfirst[ usetab]]] }}

  Return a copy of the passed string, each line indented by 4 spaces. The first line is not indented. If you want to change the number of spaces or indent the first line too you can pass additional parameters to the filter:

      {{ mytext|indent(2, True) }}
          indent by two spaces and indent the first line too.

int
  Convert the value into an integer. If the conversion doesn't work it will return `0`. You can override this default using the first parameter.
join

  Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define ith with the optional parameter:

      {{ [1, 2, 3]|join('|') }}
          -> 1|2|3

      {{ [1, 2, 3]|join }}
          -> 123

jsonencode

  JSON dump a variable. just works if simplejson is installed.

      {{ 'Hello World'|jsonencode }}
          -> "Hello World"

last
  Return the last item of a sequence.
length

  Return the length of the value. In case if getting an integer or float it will convert it into a string an return the length of the new string. If the object has no length it will of corse return 0.

  Aliases: | count

lower
  Convert a value to lowercase.
markdown

  Parse the string using markdown.

  requires the Python-markdown library.

pprint

  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)

random
  Return a random item from the sequence.
replace

  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

  Return a reversed list of the sequence filtered. You can use this for example for reverse iteration:

      {% for item in seq|reverse %}
          {{ item|e }}
      {% endfor %}

round

  Round the number to a given precision. The first parameter specifies the precision (default is `0`), the second 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.

      {{ 42.55|round }}
          -> 43
      {{ 42.55|round(1, 'floor') }}
          -> 42.5

  new in Jinja 1.1

rst

  Parse the string using the reStructuredText parser from the docutils package.

  requires docutils.

slice

  Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three div 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.

  new in Jinja 1.1

sort

  Sort a sequence. Per default it sorts ascending, if you pass it True as first argument it will reverse the sorting.

  new in Jinja 1.1

string
  Convert the value into an string.
striptags

  Strip SGML/XML tags and replace adjacent whitespace by one space.

  new in Jinja 1.1

sum

  Sum up the given sequence of numbers.

  new in Jinja 1.1

textile

  Prase the string using textile.

  requires the PyTextile library.

title
  Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.
trim
  Strip leading and trailing whitespace.
truncate

  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 try to save 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.

upper
  Convert a value to uppercase.
urlencode

  urlencode a string or directory.

      {{ {'foo': 'bar', 'blub': 'blah'}|urlencode }}
          -> foo=bar&blub=blah

      {{ 'Hello World' }}
          -> Hello%20World

urlize

  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"

wordcount
  Count the words in that string.
wordwrap
  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 true Jinja will also split words apart (usually a bad idea because it makes reading hard).
xmlattr

  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. You can disable this by passing false as only argument to the filter.

  New in Jinja 1.1

note

Jinja 1.0 and 1.1 notice

The filter operator has a pretty low priority in Jinja 1.0 and 1.1. If you want to add fitered values you have to put them into parentheses. The same applies if you want to access attributes or return values:

    correct:
        {{ (foo|filter) + (bar|filter) }}
    wrong:
        {{ foo|filter + bar|filter }}

    correct:
        {{ (foo|filter).attribute }}
    wrong:
        {{ foo|filter.attribute }}

This changed in Jinja 1.2, from that version one the filter operator has the highest priority so you can do `foo|filter + bar|filter`.

new in Jinja 1.1:

Because the application can provide additional filters you can get a documentation of all the provided filters by calling `debug.filters()`:

    {{ debug.filters() }}
        -> returns a plain text representation of all the filters

    {{ debug.filters(False) }}
        -> same as above but without the builtin ones.

## Tests

You can use the is operator to perform tests on a value:

    {{ 42 is numeric }} -> true
    {{ "foobar" is numeric }} -> false
    {{ 'FOO' is upper }} -> true

These tests are especially useful when used in if conditions.

defined

  Return true if the variable is defined:

      {% if variable is defined %}
          value of variable: {{ variable }}
      {% else %}
          variable is not defined
      {% endif %}

  See also the `default` filter.

even
  Return true of the variable is even.
lower
  Return true if the variable is lowercase.
matching

  Test if the variable matches the regular expression given. Note that you have to escape special chars using two backslashes, these are not raw strings.

      {% if var is matching @/^\d+$/ %}
          var looks like a number
      {% else %}
          var doesn't really look like a number
      {% endif %}

numeric
  Return true if the variable is numeric.
odd
  Return true if the variable is odd.
sameas

  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 %}

  New in Jinja 1.2

sequence
  Return true if the variable is a sequence. Sequences are variables that are iterable.
upper
  Return true if the variable is uppercase.

new in Jinja 1.1:

Because the application can provide additional tests you can get a documentation of all the provided tests by calling `debug.tests()`:

    {{ debug.tests() }}
        -> returns a plain text representation of all the tests

    {{ debug.tests(False) }}
        -> same as above but without the builtin ones.

new in Jinja 1.2:

If a test function expects one or no argument you can leave out the parentheses. Previously this was only possible for text functions without arguments:

    {{ foo is matching @/\s+/ }}
        is the same as
    {{ foo is matching(@/\s+/) }}

## Global Functions

Test functions and filter functions live in their own namespace. Global functions not. They behave like normal objects in the context. Beside the functions added by the application or framewhere there are two functions available per default:

range

> Works like the python range function just that it doesn't support ranges greater than `1000000`.

debug

> Function that outputs the contents of the context.

lipsum

> Generate some paragraphs of random text:

>     {{ lipsum(5) }}
>         five html paragraphs

>     {{ lipsum(2, False) }}
>         two ascii only paragraphs

> Per default a paragraph is between 20 and 100 words long. You can override this default with the third and fourth parameter:

>     {{ lipsum(10, True, 50, 200) }}
>         generate 10 HTML paragraphs between 50 and 200 words.

> new in Jinja 1.1

watchchanges

> Jinja does not provide an django like `{% ifchanged %}` tag. As replacement for this tag there is a special function in the namespace called watchchanges.

> You can use it like this:

>     {% for changed, article in watchchanges(articles, 'date', 'day') %}
>         {% if changed %}<h3>{{ articles.date.day }}</h3>{% endif %}
>         <h4>{{ article.title|e }}</h4>
>         <p>{{ article.body|e }}</p>
>     {% endif %}

> For each iteration watchchanges will check the given attribute. If it changed to the former iteration the first yielded item (in this example it's called changed) will be true, else false.

> In this example articles is a list of articles for the template with an attribute called date.day which represents the current day. To only add a new day headline if the day has changed watchchanges is now told to check articles.date.days.

> If you want to observe more than one attribute you can provide pairs:

>     {% for changed, item in watchchanges(foo, ('a', 'b'), ('a', 'c')) %}
>         ...
>     {% endfor %}

> Note that if you want to watch two first level attributes you have to either use the list syntax [] or add a colon:

>     {% for changed, item in watchchanges(foo, ['a'], ('b',)) %}
>         ...
>     {% endfor %}

> otherwise Jinja cannot differ between a pair of parentheses to group expressions or the sequence syntax.

> If you don't provide any arguments the value of the variable itself is checked.

> new in Jinja 1.1

rendertemplate

> Loads and renders a template with a copy of the current context. This works in many situations like the `{% include %}` tag, just that it does not include a template and merges it into the template structure but renders it completely independent and returns the rendered data as string.

> new in Jinja 1.1

## Global Constants

Jinja provides some special variables which cannot be overridden in templates. Those are not affected by the variable lookup:

> _, true, false, none, undefined

You cannot use those names for your own variables or macros. It's however no problem to have blocks with that name.

Notice due to a bug in Jinja 1.0 it was possible to override _, true, false, none and undefined from the template by either using {% set %} or in a for loop. While overriding true, false etc just caused nothing overriding the translation marker _ would crash the translation interface. If you want to use _ for unpacking in for loops (eg. skipping items) you have to give it a proper name:

    {% for key, ignore in mydict|dictsort %}
        {{ key|e }}
    {% endfor %}