# Filters

> Reference for OneFuse Jinja2 filters used to transform and format variable values

---

Site [llms.txt](/llms.txt)

---

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.

```jinja2
{# 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:**

```jinja2
{# Example 1 #}
HELLO

{# Example 2 #}
HELLO WORLD
```

## abs

Filter returns the absolute (non-negative) value of the argument.

**Example:**

```jinja2
{% set foo = -5 %}
{{ foo | abs }}
```

**Result:**

```text
5
```

See also: [float](#float), [int](#int), [max](#max), [min](#min), [round](#round), [sum](#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:**

```jinja2
{{ foo | attr("bar") }}
```

See also: [groupby](#groupby), [map](#map), [reject](#reject), [rejectattr](#rejectattr), [select](#select), [selectattr](#selectattr).

## batch

Filter that batches items.

It works similar to [slice](#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:**

```jinja2
{# batch(linecount, fill_with=None) #}

{% set items = ["Dev", "Prod"] %}
{%- for item in items | batch(3, 'Test') %}
  {%- for env in item %}
    {{ env }}
  {%- endfor %}
{%- endfor %}
```

**Result:**

```text
Dev
Prod
Test
```

See also: [first](#first), [join](#join), [last](#last), [length](#length), [list](#list), [slice](#slice), [sort](#sort).

## capitalize

Filter capitalizes a value.

The first character will be uppercase, all others lowercase.

**Example:**

```jinja2
{% set foo = "hello world" %}
{{ foo | capitalize }}
```

**Result:**

```text
Hello world
```

See also: [lower](#lower), [title](#title), [upper](#upper).

## center

Filter centers the value in a field of a given width.

**Example:**

```jinja2
{# center(width) #}

{% set foo = "hello world" %}
{{ foo | center(80) }}
```

**Result:**

```text
                                  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:**

```jinja2
{# default(default_value='', boolean=False) #}

{% set foo = "" %}
{{ foo | default("hello world", true) }}
```

**Result:**

```text
hello world
```

See also: [required](#required).

## dictsort

Filter sorts a python [dict](https://www.w3schools.com/python/python_dictionaries.asp) and yield (`key, value`) pairs.

Order by either key or value.

**Example:**

```jinja2
{# 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](#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:**

```jinja2
{% set foo = "&" %}
{{ foo | escape }}
```

**Result:**

```text
&amp;
```

See also: [forceescape](#forceescape), [safe](#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:**

```jinja2
{# filesizeformat(binary=False) #}
{{ myfile | filesizeformat }}
```

## first

Filter returns the first item of a sequence.

**Example:**

```jinja2
{% set items = ["Dev", "Prod"] %}
{{ items | first }}
```

**Result:**

```text
Dev
```

See also: [batch](#batch), [join](#join), [last](#last), [length](#length), [list](#list), [slice](#slice), [sort](#sort), [unique](#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:**

```jinja2
{# float(default=0.0) #}

{% set foo = 1 %}
{{ foo | float }}
```

**Result:**

```text
1.0
```

See also: [abs](#abs), [int](#int), [max](#max), [min](#min), [round](#round), [sum](#sum).

## forceescape

Enforce HTML escaping. This will double escape variables.

**Example:**

```jinja2
{% set foo = "&" %}
{{ foo | forceescape }}
```

**Result:**

```text
&amp;
```

See also: [escape](#escape), [safe](#safe).

## format

Filter applies the given values to a [printf-style](https://docs.python.org/library/stdtypes.html#printf-style-string-formatting) format string, like `string % values`.

**Example:**

```jinja2
{# format(*args, **kwargs) #}

{% set foo = "Hello" %}
{% set bar = "World" %}
{{ "%s, %s!" | format(foo, bar) }}
```

**Result:**

```text
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:**

```jinja2
{# 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](#attr), [map](#map), [reject](#reject), [rejectattr](#rejectattr), [select](#select), [selectattr](#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:**

```jinja2
{# indent(width=4, first=False, blank=False, indentfirst=None) #}

{% set foo = "hello world" %}
{{ foo | indent(2, true) }}
```

**Result:**

```text
  hello world
```

## int

Filter converts the value into an integer.

If the conversion does not work, it will return 0.

**Example:**

```jinja2
{# int(default=0, base=10) #}

{% set foo = "1" %}
{{ foo | int }}
```

**Result:**

```text
1
```

See also: [abs](#abs), [float](#float), [max](#max), [min](#min), [round](#round), [sum](#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:**

```jinja2
{# join(separator='', attribute=None) #}

{% set foo = ["Dev", "Prod"] %}
{{ foo | join(", ") }}
```

**Result:**

```text
Dev, Prod
```

See also: [batch](#batch), [first](#first), [last](#last), [length](#length), [list](#list), [slice](#slice), [sort](#sort).

## last

Filter returns the last item of a sequence.

**Example:**

```jinja2
{% set foo = ["Dev", "Prod"] %}
{{ foo | last }}
```

**Result:**

```text
Prod
```

See also: [batch](#batch), [first](#first), [join](#join), [length](#length), [list](#list), [slice](#slice), [sort](#sort), [unique](#unique).

## length

Filter returns the number of items in a container.

**Example:**

```jinja2
{% set foo = ["Dev", "Prod"] %}
{{ foo | length }}
```

**Result:**

```text
2
```

See also: [batch](#batch), [first](#first), [join](#join), [last](#last), [list](#list), [slice](#slice), [sort](#sort), [wordcount](#wordcount).

## list

Filter converts the value into a list.

If it is a string, the returned list will be a list of characters.

**Example:**

```jinja2
{% set foo = "Dev" %}
{{ foo | list }}
```

**Result:**

```text
['D', 'e', 'v']
```

See also: [batch](#batch), [first](#first), [join](#join), [last](#last), [length](#length), [slice](#slice), [sort](#sort).

## lower

Filter converts a value to lowercase.

**Example:**

```jinja2
{% set foo = "Hello World" %}
{{ foo | lower }}
```

**Result:**

```text
hello world
```

See also: [capitalize](#capitalize), [title](#title), [upper](#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:**

```jinja2
{# 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](#attr), [groupby](#groupby), [reject](#reject), [rejectattr](#rejectattr), [select](#select), [selectattr](#selectattr).

## max

Filter returns the largest item from the sequence.

**Example:**

```jinja2
{# max(case_sensitive=False, attribute=None) #}

{% set foo = [1, 2, 3] %}
{{ foo | max }}
```

**Result:**

```text
3
```

See also: [abs](#abs), [float](#float), [int](#int), [min](#min), [round](#round), [sum](#sum).

## min

Filter returns the smallest item from the sequence.

**Example:**

```jinja2
{# min(case_sensitive=False, attribute=None) #}

{% set foo = [1, 2, 3] %}
{{ foo | min }}
```

**Result:**

```text
1
```

See also: [abs](#abs), [float](#float), [int](#int), [max](#max), [round](#round), [sum](#sum).

## pprint

Filter pretty prints a variable. Useful for debugging.

**Example:**

```jinja2
{# pprint(verbose=False) #}

{{ foo | pprint }}
```

## random

Filter returns a random item from the sequence.

**Example:**

```jinja2
{% set foo = [1, 3, 5, 7, 9] %}
{{ foo | random }}
```

**Result:**

```text
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:**

```jinja2
{% set foo = '' %}
{{ foo | random_mac }}
```

**Result:**

```text
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:**

```jinja2
{{ numbers | reject("odd") }}
```

See also: [attr](#attr), [groupby](#groupby), [map](#map), [rejectattr](#rejectattr), [select](#select), [selectattr](#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:**

```jinja2
{{ users | rejectattr("is_active") }}
{{ users | rejectattr("email", "none") }}
```

See also: [attr](#attr), [groupby](#groupby), [map](#map), [reject](#reject), [select](#select), [selectattr](#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:**

```jinja2
{# 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:**

```jinja2
{# Example 1 #}
hi world

{# Example 2 #}
bba
```

## required

Filter returns an error when a rendered variable results to empty (undefined or null).

**Example:**

```jinja2
{# required(message="NO MESSAGE DEFINED") #}

{% set foo = "" %}
{{ foo | required("foo was not defined") }}
```

**Result:**

```text
ERROR: foo was not defined
```

See also: [default](#default).

## reverse

Filter reverses the object or return an iterator that iterates over it the other way round.

**Example:**

```jinja2
{% set foo = ["Dev", "Prod"] %}
{{ foo | reverse | list }}
```

**Result:**

```text
['Prod', 'Dev']
```

See also: [sort](#sort).

## round

Filter rounds the number to a given precision.

**Example:**

```jinja2
{# 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:**

```jinja2
{# Method: common #}
2.0

{# Method: floor #}
1.6

{# Method: ceil #}
1.7
```

See also: [abs](#abs), [float](#float), [int](#int), [max](#max), [min](#min), [sum](#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:**

```jinja2
{% set foo = "&" %}
{{ foo | safe }}
```

**Result:**

```text
&
```

See also: [escape](#escape), [forceescape](#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:**

```jinja2
{# select(*args, **kwargs) #}

{{ numbers | select("odd") }}
{{ numbers | select("divisibleby", 3) }}
{{ numbers | select("lessthan", 42) }}
{{ strings | select("equalto", "mystring") }}
```

See also: [attr](#attr), [groupby](#groupby), [map](#map), [reject](#reject), [rejectattr](#rejectattr), [selectattr](#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:**

```jinja2
{# selectattr(*args, **kwargs) #}

{{ users | selectattr("is_active") }}
{{ users | selectattr("email", "none") }}
```

See also: [attr](#attr), [groupby](#groupby), [map](#map), [reject](#reject), [rejectattr](#rejectattr), [select](#select).

## slice

Filter slices an iterator and return a list of lists containing those items.

**Example:**

```jinja2
{# slice(slices, fill_with=None) #}

{% set foo = ["Dev", "Prod"] %}
{{ foo | slice(3, "Test") | list }}
```

**Result:**

```text
[['Dev'], ['Prod'], ['Test']]
```

See also: [batch](#batch), [first](#first), [join](#join), [last](#last), [length](#length), [list](#list), [sort](#sort).

## sort

Filter sorts an iterable.

**Example:**

```jinja2
{# 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:**

```text
['Dev', 'Prod']
```

See also: [batch](#batch), [dictsort](#dictsort), [first](#first), [join](#join), [last](#last), [length](#length), [list](#list), [reverse](#reverse), [slice](#slice).

## split

Filter splits a string value and returns the result value(s) in an array.

**Example:**

```jinja2
{# split(delimiter='') #}

{% set foo = "hostname.domain.com" %}
{# Example 1 #}
{{ foo.split('.') }}

{# Example 2 #}
{{ foo.split('.') | first }}
```

**Result:**

```jinja2
{# Example 1 #}
['hostname', 'domain', 'com']

{# Example 2 #}
hostname
```

See also: [batch](#batch), [dictsort](#dictsort), [first](#first), [join](#join), [last](#last), [length](#length), [list](#list), [reverse](#reverse), [slice](#slice).

## string

Filter makes a string unicode if it is not already.

That way a markup string is not converted back to unicode.

**Example:**

```jinja2
{{ object | string }}
```

## striptags

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

**Example:**

```jinja2
{{ xml | striptags }}
```

## substring

Filter returns the substring.

**Example:**

```jinja2
{% set foo = "hostname" %}
{{ foo[0:4] }}
```

**Result:**

```text
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:**

```jinja2
{# sum(attribute=None, start=0) #}

{% set foo = [1, 2] %}
{{ foo | sum }}
```

**Result:**

```text
3
```

See also: [abs](#abs), [float](#float), [int](#int), [max](#max), [min](#min), [round](#round).

## title

Filter returns a title-cased version of the value.

Words will start with uppercase letters, all remaining characters are lowercase.

**Example:**

```jinja2
{% set foo = "hello world" %}
{{ foo | title }}
```

**Result:**

```text
Hello World
```

See also: [capitalize](#capitalize), [lower](#lower), [upper](#upper).

## trim

Filter strips leading and trailing characters, by default whitespace.

**Example:**

```jinja2
{# trim(chars=None) #}
{% set foo = "   hello world   " %}
{{ foo | trim }}
```

**Result:**

```text
hello world
```

See also: [truncate](#truncate), [wordwrap](#wordwrap).

## 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:**

```jinja2
{# 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:**

```jinja2
{# Example 1 #}
foo...


{# Example 2 #}
foo ba...


{# Example 3 #}
foo bar baz qux


{# Example 4 #}
foo bar(...)
```

See also: [trim](#trim), [wordwrap](#wordwrap).

## unique

Filter returns a list of unique items from the given iterable.

**Example:**

```jinja2
{# 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:**

```jinja2
{# Example 1 #}
A
B
c

{# Example 2 #}
['A', 'B', 'a', 'b', 'c']
```

See also: [first](#first), [last](#last).

## upper

Filter converts a value to uppercase.

**Example:**

```jinja2
{% set foo = "hello world" %}
{{ foo | upper }}
```

**Result:**

```text
HELLO WORLD
```

See also: [capitalize](#capitalize), [lower](#lower), [title](#title).

## urlencode

Filter quotes data for use in a URL path or query using UTF-8.

**Example:**

```jinja2
{% set foo = "https://onefuse.example.com:443" %}
{{ foo | urlencode }}
```

**Result:**

```text
https%3A//onefuse.example.com%3A443
```

See also: [urlize](#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:**

```jinja2
{# 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](#urlencode).

## wordcount

Filter counts the words in that string.

**Example:**

```jinja2
{% set foo = "hello world" %}
{{ foo | wordcount }}
```

**Result:**

```text
2
```

See also: [length](#length).

## wordwrap

Filter wraps a string to the given width.

Existing newlines are treated as paragraphs to be wrapped separately.

**Example:**

```jinja2
{# 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) }}
```

See also: [trim](#trim), [truncate](#truncate).
