To work with data in Jinja conveniently, you can use filters. Filters are functions that are applied to your data in a specific way:
To apply a filter to a variable or data structure, use the pipe character, |
, followed by the desired filter. The pipe can be understood as "so that".
For example, the upper
filter takes a string and returns it in uppercase.
{{ user["$name"] | upper }}
This code can be read as "Display the customer's name so that all letters are in uppercase."
Filters in Jinja work like functions and take at least one argument. The first argument is the value before the pipe symbol |
. Additional arguments are specified in round brackets after the filter name. If there are no additional arguments, the brackets can be omitted.
An example of a filter with no additional arguments:
{{ "orange" | upper }} {# outputs "ORANGE" #} {{ "orange" | upper() }} {# also outputs "ORANGE" #}
Example of a filter with additional arguments:
The replace
filter takes a string and two characters to replace:
{{ "apple" | replace('p', 'b') }} {# outputs "abble" #}
If you don't specify arguments, you will get an error:
{{ "apple" | replace }} {# throws error because arguments are missing #}
Filters that operate on lists create Generator objects. To convert them back to lists, use the list
filter.
{% set arr = [1, 2, 3] %} {% set arr = arr | batch(1) %} {# prints the generator object #} {{ arr }} {# prints the list of batches #} {{ arr | list }}
String filters convert string variables to strings.
{% set o = ['b1', 'a1', 'c1'] %} {{ 'List length: ' ~ o | count }} {# prints list length: 3" #} {% set o = o | join(', ') | upper %} {{ 'String length: ' ~ o | count }} {# prints string length: 14" #}
You can chain filters if the data type returned by one filter is suitable for the next filter. Filters are evaluated left to right.
{{ "apple" | upper | replace('P', 'b') }} {# outputs "AbbLE" #} {{ "apple" | replace('P', 'b') | upper }} {# outputs "APPLE" #}
center(value, width=80)
Centers the string in a field of the specified width, adding spaces on both sides. The default width is 80 characters, but you can specify a custom value.
{{ "apple" | center(10) }} {# outputs " apple " #}
capitalize(value)
Makes the first character of the string uppercase and the rest lowercase.
{{ "orange" | capitalize }} {# outputs "Orange" #}
escape(value) or e(value)
Converts special characters in a string to HTML-safe sequences.
forceescape(value)
Similar to escape(), but also escapes macro output.
format(value, *args, **kwargs)
Formats a string using old Python formatting (%
).hash(value, hash_fn, input_encoding='utf-8', output_encoding='hex')
Hashes strings using various algorithms. Parameters:
value
: the string to hash.hash_fn
: hash type (e.g. 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512').input_encoding(optional)
: input string encoding (default 'utf-8').output_encoding(optional)
: output string encoding (default 'hex', 'base64' is also supported) hmac(key, message, hash_fn, input_encoding='utf-8', output_encoding='hex')
Creates HMAC (Hash-based Message Authentication Code) using various algorithms. Parameters:
key
: string to use as key.message
: string of message to authenticate.hash_fn
: hash type (e.g. 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512').input_encoding (optional)
: encoding of input strings (default 'utf-8').output_encoding (optional)
: encoding of output string (default 'hex', 'base64' is also supported).indent(value, width=4, first=False, blank=False)
Adds indents to each line. Parameters:
width
: Number of spaces to indent all lines except the first.first
: Indent the first line.blank
: Indent blank lines.
{% set text = "Line 1\nLine 2\nLine 3" %} {{ text | indent(width=4, first=False) }} {# Outputs: Line 1 Line 2 Line 3 #}
lower(value)
Converts a string to lowercase.
{{ "Hello, World!" | lower }} {# outputs "hello, world!" #}
pprint(value, verbose=False)
Formats out the variable nicely, useful for debugging.
{{ {"name": "Alice", "age": 30, "hobbies": ["reading", "hiking"]} | pprint }} {# outputs: { 'age': 30, 'hobbies': ['reading', 'hiking'], 'name': 'Alice' } #}
replace(value, old, new, count=None)
Replaces all or the specified number of substring occurrences in a string. This filter also allows you to remove a single character occurrence by specifying an empty string as the second argument.
{{ "apple" | replace('p', 'b') }} {# outputs "abble" #}
title(value)
Converts a string to uppercase (each word starts with a capital letter).
{{ "hello, world!" | title }} {# Outputs "Hello, World!" #}
trim(value)
Removes leading and trailing spaces from a string.
{{ " Hello, World! " | trim }} {# Outputs "Hello, World!" #}
slice(value)
Extracts substrings or sublists from strings or lists. It works similarly to Python slices and allows you to specify start and end indices, as well as a step. You can also use it to cut specific characters from a string.
{{ "hello world" | slice(1, 5) }} {# outputs "ello" #} {{ "abcdefg" | slice(0, None, 2) }} {# outputs "aceg" #}
striptags(value)
Removes SGML/XML tags from a string.
{{ "Hello <b>world</b>" | striptags }} {# outputs "Hello world" #}
truncate(value, length=255, killwords=False, end='...')
Truncates a string to a given number of characters. Parameters:
length
: string length.killwords
: trim by words.end
: string to append to the end of the trimmed string.
{{ "hello world" | truncate(5) }} {# outputs "hello..." #}
upper(value)
Converts a string to uppercase.
{{ "orange" | upper }} {# outputs "ORANGE" #}
urlencode(value)
Encodes a string for use in a URL.
{{ "Hello, World!" | urlencode }} {# Outputs "Hello%2C%20World%21" #}
wordwrap(value, width=79, break_long_words=True, wrapstring=None)
Splits a string into lines of width characters. Parameters:
width
: string length.break_long_words
: break long words.wrapstring
: string to replace the new line with.
More on the format
filter
The format
filter allows you to substitute values into a string. It works the same way as the %
operator in Python.
Using with multiple arguments (args
):
You can pass values as a list, and they will be substituted in order.
{{ "Hello, %s!" | format("world") }} {# outputs "Hello, world!" #}
Using with key arguments (kwargs
):
You can provide values as named arguments. In this case, the values will be substituted into the appropriate places by keywords.
{{ "Hello, %(name)s!" | format(name="world") }} {# outputs "Hello, world!" #}
Please note: Jinja doesn't support formatting variables directly from a dictionary. Use variable=value
keyword arguments instead.
Example with multiple arguments:
{{ "Hello, %s %s!" | format("John", "Doe") }} {# outputs "Hello, John Doe!" #}
Example with key arguments:
{{ "Hello, %(first_name)s %(last_name)s!" | format(first_name="John", last_name="Doe") }} {# outputs "Hello, John Doe!" #}
abs(number)
Returns the absolute value of a number.
{{ -5 | abs }} {# outputs "5" #}
round(value, precision=0, method='common')
Rounds a number to the specified precision. Parameters:
precision (optional)
: number of decimal places (default 0).method (optional)
: rounding method (default 'common').
Rounding methods:
'common'
: rounds either up or down (common rounding).'ceil'
: always rounds up.'floor'
: always rounds down.
{{ 3.14159 | round(2) }} {# outputs "3.14" #} {{ 3.14159 | round(2, 'ceil') }} {# outputs "3.15" #} {{ 3.14159 | round(2, 'floor') }} {# outputs "3.14" #}
Iterables are lists, tuples, strings, and dictionaries.
Filters that select a single element from an iterable
attr(Object, name)
Gets the value of an object attribute. Parameters: Any object, the attribute name (string).
{{ foo | attr("bar") }} {# works like foo.bar #}
Please note: it's not used to get dictionary values by keys or list/tuple/string elements by index.
first(Iterable)
Returns the first element of the iterable.
{{ [1, 2, 3] | first }} {# outputs 1 #}
last(Iterable)
Returns the last element of the iterable.
{{ [1, 2, 3] | last }} {# outputs 3 #}
random(Iterable)
Returns a random element of the iterable.
{{ [1, 2, 3] | random }} {# Will print a random element, eg 2 #}
Filters for changing the contents of iterables
batch(value, batchSize, fill_with=None)
Groups elements into lists of a given size. Parameters: Iterable value, batch size, optional fill value.
{{ [1, 2, 3, 4, 5] | batch(2) }} {# outputs [[1, 2], [3, 4], [5]] #}
slice(value, slices, fill_with=None)
Divides the iterable into the given number of pieces. Parameters: The iterable value, the number of pieces, an optional value to fill with.
{{ [1, 2, 3, 4, 5] | slice(2) }} {# outputs [[1, 2, 3], [4, 5]] #}
map(attribute)
Looks up an attribute for each element in the list.
{{ users | map(attribute='name') }} {# Lists the names of all users #}
map(filter)
Applies a filter to each element of the list.
{{ ["apple", "banana"] | map("upper") }} {# outputs ["APPLE", "BANANA"] #}
rejectattr(attribute, test, *testArgs)
Rejects elements where the attribute passes the test. Parameters: Attribute (string), test, arguments for the test.
{{ users | rejectattr("is_active", "equalto", True) }} {# outputs users whose is_active is not True #}
select(test, *testArgs)
Selects elements that passed the test. Parameters: Test, arguments for the test.
{{ [1, 2, 3, 4] | select("odd") }} {# outputs [1, 3] #}
selectattr(attribute, test, *testArgs)
Selects elements whose attribute passes the test. Parameters: Attribute (string), test, arguments for the test.
{{ users | selectattr("is_active", "equalto", True) }} {# Will only show active users #}
If no test is specified, the attribute’s value will be evaluated as a boolean.
unique(value)
Returns a list of unique elements from the iterable.
{{ [1, 2, 2, 3] | unique }} {# outputs [1, 2, 3] #}
reverse(value)
Reverses the order of elements.
{{ [1, 2, 3] | reverse }} {# outputs [3, 2, 1] #}
sort(value, reverse=False, case_sensitive=False, attribute=None)
Sorts the elements in ascending order. Parameters: An iterable, optional parameters for reverse sorting, case sensitivity, and sorting by attribute.
Default sorting:
{{ [3, 1, 2] | sort }} {# outputs [1, 2, 3] #}
Reverse sorting:
{{ [3, 1, 2] | sort(reverse=True) }} {# Outputs [3, 2, 1] #}
Sorting strings case sensitive:
{{ ["apple", "Banana", "cherry"] | sort(case_sensitive=True) }} {# Outputs ["Banana", "apple", "cherry"] #}
Sorting by attribute:
{{ users | sort(attribute="age") }} {# Outputs users sorted by age #}
float(value, default=0.0)
Converts value to a float. Parameters: Any value, optional default.
{{ "3.14" | float }} {# Outputs 3.14 #} {{ "abc" | float(1.23) }} {# Outputs 1.23 #}
int(value, default=0, base=10)
Converts value to an integer. Parameters: Any value, optional default, base.
{{ "42" | int }} {# Outputs 42 #} {{ "0x2A" | int(base=16) }} {# Outputs 42 #} {{ "abc" | int(7) }} {# Outputs 7 #}
string(value)
Converts value to Unicode string
{{ 123 | string }} {# Prints "123" #}
list(value)
Converts iterable to list.
{{ "abc" | list }} {# Prints ["a", "b", "c"] #} {{ {"a": 1, "b": 2} | list }} {# Prints ["a", "b"] #}}
safe(value)
Marks value as safe
{{ "<div>Hello</div>" | safe }} {# Prints <div>Hello</div> #}
default(value, default_value='', boolean=False)
Returns value if defined, otherwise default value. Parameters: Any value, default value, flag to account for empty strings, and None.
{{ my_variable | default("not defined") }} {# outputs "not defined" if my_variable is not defined #}
dictsort(value, case_sensitive=False, by='key')
Sorts a dictionary and returns a list of tuples of (key, value) pairs. Parameters: Dictionary, case-sensitive flag, sort by key or value.
{{ {"b": 1, "a": 2} | dictsort }} {# Outputs [("a", 2), ("b", 1)] #}
filesizeformat(value, binary=False)
Formats a value into a string with a human-readable file size. Parameters: Numeric value, flag to use binary prefixes.
{{ 1024 | filesizeformat }} {# Outputs "1.0 KB" #} {{ 1048576 | filesizeformat(binary=True) }} {# Outputs "1.0 MiB" #}
join(value, d='', attribute=None)
Returns a string that is the concatenation of the elements in the iterable. Parameters: Iterable, delimiter, attribute.
{{ ["a", "b", "c"] | join(", ") }} {# Outputs "a, b, c" #}
length(value)
Returns the number of elements in the iterable.
{{ [1, 2, 3] | length }} {# Outputs 3 #}
sum(iterable, attribute=None, start=0)
Returns the sum of the numbers in the sequence plus the value of the start parameter. Parameters: Iterable, optional attribute (string), start value (integer).
Sum of numbers in the list:
{{ [1, 2, 3] | sum }} {# Outputs 6 #}
Sum of numbers in a list with initial value:
{{ [1, 2, 3] | sum(start=10) }} {# Outputs 16 #}
Sum of attribute values in object list:
{{ items | sum(attribute='price') }} {# Sums the values of the 'price' attribute of each element in items #}
wordcount(value)
Counts the number of words in a string
{{ "Hello world" | wordcount }} {# Outputs 2 #}
xmlattr(value, autospace=True)
Creates an SGML/XML attribute string based on the elements in the dictionary. Parameters: Dictionary, autospace flag
{{ {"id": "123", "class": "button"} | xmlattr }} {# Outputs 'id="123" class="button"' #}
Other articles on Jinja:
Basic Jinja Syntax
Data Structure in Jinja
Personalization with Jinja