Builtin Filters
These are invoked with the pipe (|) syntax, for example:
{{ "hello" | capitalize }}
{{ [1, 2, 3]|join('|') }}
Text
capitalize
Capitalize a value. The first character will be uppercase, all others lowercase.
escape
Replace the characters &, <, >, ', and " in the string with HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML.
If the object has an __html__ method, it is called and the return value is assumed to already be safe for HTML.
You can also use the alias e instead.
indent
Indent the given string or markup by a specified width, with options for the first line and blank lines.
do_indent(
s: str | markupsafe.Markup,
width: int = 4,
first: bool = False,
blank: bool = False
) -> str
| Argument | Description |
|---|---|
s |
The string or markup to indent. |
width |
The number of spaces to use for indentation, or a string to use as the indentation. Defaults to 4. |
first |
Whether to indent the first line. Defaults to False. |
blank |
Whether to indent blank lines. Defaults to False. |
Returns: A copy of the string with each line indented by the specified width. The first line and blank lines are not indented by default unless specified.
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.
do_replace(
s: Any,
old: Any,
new: Any,
count: int | None = None
) -> str
| Argument | Description |
|---|---|
s |
The string in which to perform the replacement. |
old |
The substring to be replaced. |
new |
The substring to replace with. |
count |
The maximum number of replacements to perform. Defaults to replacing all occurrences. |
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 #}
safe
Mark a value as safe HTML, preventing it from being escaped.
str
Convert an object to a string if it isn’t already.
This preserves a Markup string rather than converting
it back to a basic string, so it will still be marked as
safe and won’t be escaped again.
striptags
Strip HTML tags from a string and unescape HTML entities.
title
Convert a string to title case.
tojson
Convert a value to a JSON string, encoding potentially unsafe characters for HTML.
do_tojson(
value,
indent=None
) -> str
| Argument | Description |
|---|---|
value |
The value to convert to JSON. |
indent |
The indentation level for pretty-printing the JSON. Defaults to None. |
trim
Trim leading and trailing characters from a string.
truncate
Truncate a string to a specified length.
do_truncate(
value: str,
length: int = 255,
killwords: bool = False,
end: str = '...',
leeway: int = 4
) -> str
| Argument | Description |
|---|---|
value |
The string to truncate |
length |
The maximum length of the returned string, including the end string if truncation occurs |
killwords |
Whether to cut the text at length, or discard the last word |
end |
The string to append if truncation occurs |
leeway |
The tolerance margin for truncation. Strings that only exceed the length by this amount will not be truncated. |
The length is specified with the second parameter (length) which defaults to 255.
If the third parameter (killwords) 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 ("...").
You can specify a different sign using the fourth (end) parameter.
Strings that only exceed the length by the tolerance margin given in the fifth (leeway)
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..." #}
lower
Convert a string to lowercase.
upper
Convert a string to uppercase.
urlencode
URL-encode a string or an iterable of key-value pairs.
wordcount
Count the number of words in a string.
wordwrap
Wrap a string to a specified width.
do_wordwrap(
s,
width=79,
break_long_words=True,
wrapstring=None,
break_on_hyphens=True
) -> str
| Argument | Description |
|---|---|
s |
The string to wrap. |
width |
The maximum line width. |
break_long_words |
Whether to break long words. |
wrapstring |
The string to use for line breaks. |
break_on_hyphens |
Whether to break on hyphens. |
{{ pride_and_prejudice_intro | wordwrap(30) }}
{# ->
It is a truth universally ack
nowledged, that a single man
in possession of a good fortu
ne, must be in want of a wife
#}
Numbers
abs
Return the absolute value of the argument.
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 default parameter.
do_float(
value: Any,
default: float = 0.0
) -> float
| Argument | Description |
|---|---|
value |
The value to convert to a float. |
default |
The default value to return if conversion fails. Defaults to 0.0. |
{{ "123" | float }}
{# => 123.0 #}
{{ "abc" | float }}
{# => 0.0 #}
int
Convert the given value to an integer.
If the conversion doesn’t work it will return 0.
You can override this default using the default parameter.
do_int(
value: Any,
default: int = 0,
base: int = 10
) -> int
| Argument | Description |
|---|---|
value |
The value to convert to an integer. |
default |
The default value to return if conversion fails. Defaults to 0. |
base |
The base to use for conversion if the value is a string. Defaults to 10. |
You can also override the default base (10), which handles input
with prefixes such as 0b, 0o and 0x for bases 2, 8 and 16
respectively. The base is ignored for decimal numbers and non-string values.
{{ "123" | int }}
{# => 123 #}
{{ "abc" | int }}
{# => 0 #}
{{ "abc" | int(base=16) }}
{# => 2748 #}
{{ "0xabc" | int }}
{# => 2748 #}
Returns: The converted integer, or the default value if conversion fails.
max
Return the maximum element from an iterable, optionally considering case sensitivity and an attribute.
do_max(
value: collections.abc.Iterable,
case_sensitive: bool = False,
attribute: str | None = None
) -> Any
| Argument | Description |
|---|---|
value |
The iterable from which to find the maximum element. |
case_sensitive |
Treat upper and lower case strings as distinct. |
attribute |
The attribute to use for comparison, if applicable. |
min
Return the minimum element from an iterable, optionally considering case sensitivity and an attribute.
do_min(
value: collections.abc.Iterable,
case_sensitive: bool = False,
attribute: str | None = None
) -> Any
| Argument | Description |
|---|---|
value |
The iterable from which to find the minimum element. |
case_sensitive |
Treat upper and lower case strings as distinct. |
attribute |
The attribute to use for comparison, if applicable. |
round
Round a floating-point number to a specified number of decimal places.
do_round(
value: float,
ndigits: int | None = None
) -> float
| Argument | Description |
|---|---|
value |
The number to round. |
ndigits |
The number of decimal places to round to. If None, rounds to the nearest integer. |
range
Return a range object based on the given start, stop, and step values.
do_range(
start: int,
stop: int | None = None,
step: int = 1
) -> range
| Argument | Description |
|---|---|
start |
The starting value of the range. |
stop |
The ending value of the range. If None, the range starts from 0. |
step |
The step size between consecutive values in the range. |
sum
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.
do_sum(
iterable: collections.abc.Iterable,
attribute: str | None = None,
start: int = 0
) -> int
| Argument | Description |
|---|---|
iterable |
The iterable of items to sum. |
attribute |
An optional attribute to extract from each item before summing. |
start |
The starting value for the sum. Defaults to 0. |
It is also possible to sum up only certain attributes:
Total: {{ items|sum(attribute='price') }}
Objects & Collections
attr
Get an attribute or item from an object or a dict, or from each one in a list of them.
do_attr(
value: Any,
name: Any,
default: Any = None
) -> Any
| Argument | Description |
|---|---|
value |
An object, a dict, or a list of them. A string or a dict is never treated as a list. |
name |
The name of the attribute or item to get. Use dots to go deeper: "address.city". |
default |
The value to use where the attribute or item doesn't exist. |
{{ user | attr("name") }}
{{ user | attr("nickname", default="?") }}
It is the same as user.name, but with a default, and the name can
be a variable:
{% for column in ["name", "email", "phone"] %}
<td>{{ user | attr(column, default="-") }}</td>
{% endfor %}
Use dots to go deeper, in objects and in dicts:
{{ user | attr("address.city", default="?") }}
{{ {"address": {"city": "Lima"}} | attr("address.city") }} {# Lima #}
With a list, or anything else you can loop over (a tuple, a query...), you get a list with the value of each one:
Users on this page: {{ users | attr("name", default="?") | join(", ") }}
Cities: {{ users | attr("address.city") | unique | sort | join(", ") }}
Total: {{ order.lines | attr("price") | sum }}
Returns:
The value, or a list of values if value is a list.
batch
Batch the given iterable into lists of the specified line count, optionally filling the last batch with a specified value.
do_batch(
value: collections.abc.Iterable[typing.Any],
linecount: int,
fill_with: Any = None
) -> collections.abc.Generator[list[typing.Any], None, None]
| Argument | Description |
|---|---|
value |
The iterable to batch. |
linecount |
The number of items per batch. |
fill_with |
The value to fill the last batch with if it has fewer items than linecount. Defaults to None. |
<table>
{%- for row in items | batch(3, ' ') %}
<tr>
{%- for column in row %}
<td>{{ column }}</td>
{%- endfor %}
</tr>
{%- endfor %}
</table>
Returns: Lists of items from the iterable, each with length linecount (except possibly the last one if fill_with is None).
default
Replaces a missing value with the passed default value, otherwise the value of the variable:
do_default(
value: Any,
default_value: Any = '',
boolean: bool = False
) -> Any
| Argument | Description |
|---|---|
value |
The value to check for being undefined or falsy. |
default_value |
The default value to return if the value is undefined or falsy. |
boolean |
Whether to consider falsy values as missing. Defaults to False. |
{{ data.value | default('value is not defined') }}
If you want to use default with variables that evaluate to False
you have to set the boolean parameter to True:
{{ '' | default('the string was empty', true) }}
Aliased as d in the filters dictionary.
dictsort
Sort the given dictionary by key or value, with optional case sensitivity and reverse order.
do_dictsort(
value: dict[typing.Any, typing.Any],
case_sensitive: bool = False,
by: str = 'key',
reverse: bool = False
) -> list[tuple[typing.Any, typing.Any]]
| Argument | Description |
|---|---|
value |
The dictionary to sort. |
case_sensitive |
Whether the sorting should be case-sensitive. Defaults to False. |
by |
Whether to sort by "key" or "value". Defaults to "key". |
reverse |
Whether to sort in reverse order. Defaults to False. |
{# sort the dict by key, case insensitive #}
{% for key, value in mydict|dictsort %}
{# sort the dict by key, case insensitive, reverse order #}
{% for key, value in mydict|dictsort(reverse=true) %}
{# sort the dict by key, case sensitive #}
{% for key, value in mydict|dictsort(true) %}
{# sort the dict by value, case insensitive #}
{% for key, value in mydict|dictsort(false, 'value') %}
Returns: A list of tuples representing the sorted dictionary items.
enumerate
Enumerate a given iterable, starting from the specified index.
first
Return the first item of the given iterable, or None if it is empty.
{{ [1, 2, 3] | first }}
{# => 1 #}
groupby
Group a sequence of objects by an attribute using Python’s itertools.groupby().
do_groupby(
value: collections.abc.Iterable[typing.Any],
attribute: str,
default: Any = None,
case_sensitive: bool = False
) -> list[jx.filters._GroupTuple]
| Argument | Description |
|---|---|
value |
The iterable of items to group. |
attribute |
The attribute to group by. |
default |
The default value to use if the attribute is missing. Defaults to None. |
case_sensitive |
Whether the grouping should be case-sensitive. Defaults to False. |
The attribute can use dot notation for nested access, like "address.city". Unlike Python’s groupby, the values are sorted first so only one group is returned for each unique value.
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.
<ul>{% for city, items in users|groupby("city") %}
<li>{{ city }}
<ul>{% for user in items %}
<li>{{ user.name }}
{% endfor %}</ul>
</li>
{% endfor %}</ul>
groupby yields namedtuples of (grouper, list), which can be used instead
of the tuple unpacking above. grouper is the value of the attribute, and list
is the items with that value.
<ul>{% for group in users|groupby("city") %}
<li>{{ group.grouper }}: {{ group.list|join(", ") }}
{% endfor %}</ul>
You can specify a default value to use if an object in the list does not have the given attribute.
<ul>{% for city, items in users|groupby("city", default="NY") %}
<li>{{ city }}: {{ items|attr("name")|join(", ") }}</li>
{% endfor %}</ul>
Like the sort filter, sorting and grouping is case-insensitive by default.
The key for each group will have the case of the first item in that group of values.
For example, if a list of users has cities ["CA", "NY", "ca"], the “CA”
group will have two values. This can be disabled by passing case_sensitive=True.
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 it with the optional parameter:
do_join(
value: collections.abc.Iterable,
joiner: str = '',
attribute: str | None = None
) -> str
| Argument | Description |
|---|---|
value |
The iterable whose elements are to be joined. |
joiner |
The string to use as a separator between elements. Defaults to an empty string. |
attribute |
The attribute to use for each element, if applicable. |
{{ [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') }}
last
Return the last item of the given sequence, or None if it is empty.
do_last(
seq: collections.abc.Reversible[typing.Any]
) -> Any
| Argument | Description |
|---|---|
seq |
The sequence to take the last item from. |
{{ [1, 2, 3] | last }}
{# => 3 #}
It doesn't work with a generator, like the result of map or unique:
make it a list first, with the list filter.
len
Return the length of the given value.
list
Convert the given iterable into a list. With a string, the result is a list of its characters.
do_list(
value: collections.abc.Iterable[typing.Any]
) -> list[typing.Any]
| Argument | Description |
|---|---|
value |
The iterable to convert. |
{{ titles | map("upper") | list }}
map
Applies a filter to each item of a list, or of anything else you can loop over. Pass the name of the filter, and its arguments after it:
{{ titles | map("upper") | join(", ") }}
{{ prices | map("round", 2) | join(", ") }}
Instead of the name of a filter you can pass a function, or anything else you can call, that the component has: a global or one of its arguments. Each item is its first argument.
{# def format_price #}
{{ prices | map(format_price) | join(", ") }}
To get an attribute of each item, use the attr filter instead:
users | attr("name").
random
Return a random item from the sequence.
reverse
Reverse an iterable.
slice
Slice an iterator and return a list of lists containing those items.
Useful if you want to, for example, create a <div> containing
three <ul> tags that represent columns:
do_slice(
value: collections.abc.Iterable,
slices: int,
fill_with: Any = None
) -> collections.abc.Generator[list, None, None]
| Argument | Description |
|---|---|
value |
The iterable to slice. |
slices |
The number of slices to create. |
fill_with |
An optional value to fill in the slices if they are uneven. |
<div class="columnwrapper">
{%- 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
Sort an iterable using Python’s sorted().
do_sort(
value: collections.abc.Iterable,
reverse: bool = False,
case_sensitive: bool = False,
attribute: str | None = None
) -> list
| Argument | Description |
|---|---|
value |
The iterable to sort. |
reverse |
Whether to sort in reverse order. Defaults to False. |
case_sensitive |
Whether the sort should be case-sensitive. Defaults to False. |
attribute |
An optional attribute to extract from each item for sorting. |
{% for city in cities|sort %}
...
{% endfor %}
The sort is stable, it does not change the relative order of elements that compare equal. This makes it is possible to chain sorts on different attributes and ordering.
{% for user in users|sort(attribute="name")
|sort(reverse=true, attribute="age") %}
...
{% endfor %}
As a shortcut to chaining when the direction is the same for all attributes, pass a comma separate list of attributes.
{% for user in users|sort(attribute="age,name") %}
...
{% endfor %}
unique
Yield unique items from the given iterable.
do_unique(
value,
case_sensitive=False,
attribute=None
) -> collections.abc.Iterator
| Argument | Description |
|---|---|
value |
The iterable to process. |
case_sensitive |
Whether to consider case when determining uniqueness. |
attribute |
An optional attribute to use for uniqueness comparison. |
{{ ['foo', 'bar', 'foobar', 'FooBar'] | unique }}
{# => ['foo', 'bar', 'foobar'] #}
The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter.
zip
Zip multiple iterables together.
do_zip(
*args: collections.abc.Iterable,
*,
strict: bool = False
) -> collections.abc.Iterator[tuple]
| Argument | Description |
|---|---|
*args |
The iterables to zip. |
strict |
Whether to enforce that all iterables have the same length. |
Returns: An iterator of tuples, where the i-th tuple contains the i-th element from each of the input iterables.