Jinja Filters
To effectively work with your data in Jinja, you sometimes need to pick and choose and modify the bits that are important to you. To enable you to do this, Jinja offers a functionality called filters. You can think of filters as pure functions applied to your data structure that takes as input your data and returns them modified in a certain way. Even though filters return your data modified, they do not produce side effects. Consequently, your data will not be affected by applying a filter on them. Although the name filter suggests that the data returned by the filter call should be somewhat reduced, filters offer a broader functionality. There are quite a few filters available, this article will cover the most important ones, others will be listed.
Filter syntax
To apply a filter to your variable or a data structure, you need to use the pipe symbol | and then a filter of your choice. You can read the pipe symbol as "such that". For instance, the filter upper
takes as input a string and returns it with all of its letters in upper case. Hence, the following code: {{ customer["name"] | upper }}
could be read as Output the customer name such that its letters are uppercase. This might help you to understand the semantics of filters.
Filters and arguments
Because filters are basically functions, they require at least one argument. The first (main) argument in the documentation below is the value before the pipe symbol, but extra arguments may be needed. In that case you have to include them in round brackets after the filter name. Otherwise, the round brackets are optional. When the documentation encloses an argument in square brackets, it is optional, also if a default value is mentioned.
For instance, the replace
filter takes as input a string and two characters as required extra arguments. Then, it outputs the string with all occurrences of the first character replaced by the second character. The code below demonstrates the use of brackets.
{# Example of filter without extra arguments #}
{{ "orange" | upper }}
{{ "orange" | upper() }}
// both work and output "ORANGE"
{# A non example and example of filters with extra arguments #}
{{ "apple" | replace }}
// throws error because arguments are missing
{{ "apple" | replace('p', 'b') }}
// this works and output "abble"
All filters that create Lists or work on Lists create Generator objects instead of Lists. To convert these objects back to Lists, use "list" filter at the end
{% set arr = [1, 2, 3] %}
{# the same goes for filters like map(), slice(), select(), selectattr(), reject(), rejectattr() #}
{% set arr = arr | batch(1) %}
{# this prints the generator object #}
{{ arr }}
{# this prints the list of batches #}
{{ arr | list }}
Using String filters on non-String variables casts the variables to Strings.
{% set o = ['b1', 'a1', 'c1'] %}
{{ 'List length: ' ~ o | count }}
{% set o = o | upper %}
{{ 'String length: ' ~ o | count }}
{# Prints:
List length: 3
String length: 18
#}
Chaining filters
You can also chain filters as long as the output type of one filter matches the input type of the filter that it is chained to. Filters are evaluated as you read them, left to right. Therefore, {{ "apple" | upper | replace('P', 'b') }}
will output "AbbLE"
, but {{ "apple" | replace('P', 'b') | upper }}
will output "APPLE"
.
Filters available in Bloomreach Engagement
You can also see the reference here, though our implementation of Jinja does not support some of the builtin filters.
Filters that are not supported
groupby()
tojson()
max()
min()
Filters that modify strings
b64encode(value, [encoding])
Parameters: String value to be encoded, Optional encoding
Output: the string form the input encoded by base 64 encoding.
Encodes a String into a base64 sequence. Optionally, encoding can be specified as a second argument, the function will apply str.encode(), see Standard encodings for list of possible encodings.
base 64 URL encoding example
Encodes a String URL, equivalent to using the JavaScript base64url.encode(value)
{% set data_encoded = '{"sub":"1234567890","name":"John Doe","iat":1516239022}' | b64encode | replace("/", "_") | replace("+", "-") | replace("=", "") %}
b64decode(value, [encoding])
Parameters: String value, Optional encoding
Output: the string from the input decoded from base 64 encoding.
Decodes a string interpreted as a base64 sequence. Optionally, encoding can be specified as a second argument, the function will apply str.encode(), see Standard encodings for list of possible encodings.
center(value, width=80)
Parameters: String value, Number width
Output: the string from the input centered in a field of the given width
Centers the value in a field of a given width, adding spaces ' ' on both sides as necessary.
Similar to str.center()
, str.ljust()
or str.rjust()
.
capitalize(value)
Parameters: String value
Output: the string from the input with its first character in Upper case
Capitalizes a value. The first character will be uppercase, all others lowercase. Same as str.capitalize().
Equivalent to str.capitalize()
escape(value)
or e(value)
Parameters: String value
Output: the string from the input converted into html safe sequence by sanitising '&', '<', '>', ‘ (singlequote), and ” (doublequote).
Convert the characters '&', '<', '>', ‘ (single-quote), and ” (double-quote) in a string 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.
forceescape(value)
Parameters: String value
Output: the string from the input converted into html safe sequence by sanitising '&', '<', '>', ‘ (singlequote), and ” (doublequote).
Similar to escape(), but forces also the output of macros to be escaped.
format(value, \* args, \* \*kwargs)
Parameters: String value, Either *args or ** kwargs
Output: the string from the input formatted by the old python formatting.
Applies old Python string formatting ( % ) on an object. To learn how to use the old Python string formatting, see Old python formatting. The list of supported types and their formatting codes can be seen in the print style formatting in PythonDocs.
hash(value, hash_fn, input_encoding='utf-8', output_encoding='hex')
Parameters: String value, String the type of the hash, Optional input encoding, Optional output encoding
Output: the value from the input hashed by the type of the hash.
Returns hashed String. Available algorithms for hash_fn are: 'md5', 'sha1', 'sha224', 'sha256', 'sha384', and 'sha512' Optionally, input and output encoding can be specified. For list of possible input encodings see Standard encodings. Supported output encodings are hex and base64.
hmac(key, message, hash_fn, input_encoding='utf-8', output_encoding='hex')
Parameters: String value as the key, String value as the message, String the type of the hash, Optional encoding
Output: HMAC string.
Returns a Hash-based message authentication code string based on the supplied key, message. Available algorithms for hash_fn are: 'md5', 'sha1', 'sha224', 'sha256', 'sha384', and 'sha512' Optionally, input and output encoding can be specified. For a list of possible input encodings see Standard encodings. Supported output encodings are hex and base64.
For example, to generate a JWT token you could use the following code:
{# generate base64url-encoded strings out of JSONs #}
{# replace calls are needed to convert the string from usual base64 to base64url #}
{% set header_encoded = '{"alg":"HS256","typ":"JWT"}' | b64encode | replace("/", "_") | replace("+", "-") | replace("=", "") %}
{% set data_encoded = '{"sub":"1234567890","name":"John Doe","iat":1516239022}' | b64encode | replace("/", "_") | replace("+", "-") | replace("=", "") %}
{% set data = header_encoded ~ "." ~ data_encoded %}
{# call hmac filter #}
{% set signature = "secretkey" | hmac(msg=data, hash_fn="sha256", output_encoding="base64") | replace("/", "_") | replace("+", "-") | replace("=", "") %}
{{ header_enoded ~ "." ~ data_encoded ~ "." ~ signature }}
{# eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.8TLPbKjmE0uGLQyLnfHx2z-zy6G8qu5zFFXRSuJID_Y #}
indent(value, width=4, first=False, blank=False)
Parameters: String value, Number width, Boolean first, Boolean blank
Output: the value from the input indented by the Number specified by width
Returns a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default.
Meaning of the Parameters:
- width – Number of spaces to indent by.
- first – Don’t skip indenting the first line.
- blank – Don’t skip indenting empty lines.
lower(value)
Parameters: String value
Output: the value from input with all characters put to lower case.
Converts a value to lowercase.
Similar to str.lower()
.
pprint(value, verbose=False)
Parameters: String value, Optional Boolean verbose
Output: the string from the input formatted nicely
Pretty prints a variable. Useful for debugging. For instance, it Prints dictionary pairs on separate lines.
replace(value, old, new, count=None)
Parameters: String value, String old, String new, Integer Optional count
Output: the supplied value with all or a specified number of occurrences of the supplied substring replaced with the other supplied substring.
Returns 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.
Similar to str.replace().
remove_accents(value)
Parameters: String value
Output: the supplied value with accents removed.
Attempts to remove accents from non-ASCII characters in the string, for example converts "Déjà vu" to "Deja vu".
title(value)
,
Parameters: String value
Output: the supplied value transformed to an English title cased version
Returns a title cased version of the value. In other words, the words of the supplied string are outputted starting with uppercase letters, all remaining characters are lowercase.
Same as str.title()
.
trim(value)
Parameters: String a value from which white spaces will be trimmed
Output: the value from the input with the leading and trailing whitespaces removed
Strips leading and trailing whitespace.
Same as the default behavior of str.strip()
.
striptags(value)
Parameters: String value
Output: the value from the input with SGML/XML tags removed.
Strips SGML/XML tags and replace adjacent whitespace by one space.
truncate(value, length=255, killwords=False, end='...', )
Parameters: String value, Integer length, Optional Boolean killword, Optional String end
Output: the given string reduced to the number of given characters
Returns a truncated copy of the string. The length is specified with the first parameter which defaults to 255. If the second 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 String specified by the third argument, end, default an ellipsis sign ("..."). Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated.
upper(value)
Parameters: String value
Output: the input string with all characters turned to uppercase.
Convert a value to uppercase.
Same as str.upper()
.
urldecode(value)
Parameters: String value
Output: the input value decoded from URL encoding.
Decodes String from URL-compatible encoding (uses UTF-8 encoding).
For URL encoding refference, see HTML URL Encoding Reference
urlencode(value)
Parameters: String value
Output: the input value encoded in the URL encoding
This filter escapes strings for use in URLs (uses UTF-8 encoding). It accepts both dictionaries and regular strings as well as pairwise iterables.
For URL encoding refference, see HTML URL Encoding Reference
Urlencode in Jinja
When given a string,
/
is not quoted. HTTP servers treat/
and%2F
equivalently in paths. If you need quoted slashes, use the|replace ("/", "%2F")
filter.For more information, explore Jinja Documentation .
urlize(value, trim_url_limit=None, nofollow=False, target=None)
Parameters: String value, Optional Integer trim_ur_limit, Optional Boolean nofollow, Optional String target
Output: HTML tag <a>
html tags with the string from the input as href property.
Converts URLs in plain text into clickable links by wrapping it in <a>
tags with href property.
For URL encoding refference, see HTML URL Encoding Reference
For reference on nofollow attribute see Use rel=\nofollow\ for specific links and for the target tag see HTML target Attribute
Parameters:
- trim_url_limit – Length to trim the url to.
- nofollow – Adds rel="nofollow" if true.
- target – Adds target=targetValue.
wordwrap(value, width=79, break_long_words=True, wrapstring=None)
Parameters: String value, Number width (optional), default = 79, Boolean breaklong_words (optional), default = True, _String wrapstring, default = None.
Output: the input value wrapped with the wrapstring
Returns 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 false Jinja will not split words apart if they are longer than width. By default, the newlines will be the default newlines for the environment, but this can be changed using the wrapstring keyword argument.
hexencode(value, [encoding])
Parameters: String value to be encoded, Optional encoding
Output: the string form the input encoded by hexadecimal encoding.
Encodes a String into a hexadecimal sequence.
hexdecode(value, [encoding])
Parameters: String value, Optional encoding
Output: the string from the input decoded from hexadecimal encoding.
Decodes a string interpreted as a hexadecimal sequence.
{% set long_string %}
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
{% endset %}
{{ long_string | wordwrap(width=45, break_long_words=True, wrapstring="<br>") }}
{# Outputs:
Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.
#}
More on the format filter
Format filter arguments can be either a sequence of values that are assigned to the %
operator sequentially in case of args. Or in the case of kwargs, they can be given as a sequence of keyword arguments in the form keyword=value
, in which case the values are assigned to the keywords. Moreover, Jinja string formatting does not support formatting the variables from a dictionary. Instead, add the values as variable=value
keyword arguments.
{# Example of using args #}
{{ '%s after %s, %d by %d' | format('One', 'another', 1, 1) }}
// prints 'One after another, 1 by 1'
{# Example of using kwargs #}
{{ 'These %(items)s have %(verb)s argument order.'|format(verb='swapped', items='words') }}
// prints 'These words have swapped argument order.'
Format filter
Mixing sequential and keyword assignment throws an error, so you have to choose either of them.
Filters that modify Numbers
abs(Number)
Parameters: a Number
Output: the absolute value of the Number
Returns the absolute value of the argument.
round(value, precision=0, method='common')
Parameters: Float value, Optional Integer precision, Optional String method
Output: the Number from the input rounded by the given method to the given precision
Rounds the Number to a given precision. The first parameter specifies the precision (default is 0), the second the rounding method:
Possible values for the method parameter:
'common' rounds either up or down
'ceil' always rounds up
'floor' always rounds down
If you don’t specify a method 'common' is used.
Filters that modify in Iterables
As a reminder, the Iterables are Lists, Tuples, Strings, and Dictionaries.
Filters that select a single item from Iterables
attr(Object, name)
Parameters: Any object, String name
Output: the value of the attribute of the given name from the given object
This filter is used to get an attribute of an object. foo | attr("bar")
works like foo.bar
. The difference is that unlike accessing the attributes with .
, the attr filter does not search for an item if the attribute with the given name does not exist. When used on the available data types, this filter can be used to get data type's properties and methods. Note the difference between a Dictionary and an Object in Jinja. Attr filter cannot be used to get Dictionary values by keys, nor to get List/Tuple/String items by index.
first(Iterable)
Parameters: Iterable value
Output: Any The first item from the given iterable
Returns the first item of an Iterable. It is equivalent to myIterable[0]
. If the given iterable is a dictionary, the filter returns the first key.
last(Iterable)
Parameters: Iterable value
Output: Any The last item from the given iterable
Returns the last item of an Iterable. It is equivalent to [myIterable][0][ myIterable | length 1 ]
. If the given iterable is a dictionary, the filter returns the last key.
random(Iterable)
Parameters: Iterable
Output: Any A random item from the given iterable
Returns a random item of an Iterable. If the given iterable is a dictionary, the filter returns a random key.
Filters that modify the content of Iterables
batch( value, batchSize, dos fill_with=None)
Input: Iterable value, Integer batchsize, Any fill_with
Output: Items from the given iterable batched to groups of the given batch size
A filter that batches items. It works like slice (see below) just the other way round (instead of specifying the Number of batches, the size of the batches is specified). It returns a list of lists with the given Number of items. If you provide a second parameter this is used to fill up missing items.
{# initialise myList #}
{% set myList = [1, 2, 3, 4, 5] %}
{# output myList filtered by batch with parameters 2 and 999 #}
{{ myList | batch(2, fill_with=999) | list }}
Output: [ [1, 2], [3, 4], [5, 999 ]
slice(value, slices, fill_with=None)
Parameters: Iterable value, Integer slices Number of slices, Optional Any fill_with any value
Output:: the supplied iterable sliced into the Number of supplied slices with gaps filled with the value of fill_with
Slices an iterable and return a list of lists containing those items. Just like batch just the other way round (instead of specifying the size of batches, the Number of batches is specified). If you pass it a second argument it’s used to fill missing values on the last iteration.
{# Initialise myList #}
{% set myList = [1, 2, 3, 4, 5] %}
{# print the value of myList filtered by slice with parameters 2 and 99 #}
{{ myList | slice(2, fill_with=999) | list }}
Output: [ [1, 2, 3], [4, 5, 999] ]
map( attribute=attributeName)
Parameters: String attribute attribute name
Output: Any values from the list that either match the supplied attribute
Looks up an attribute for each of the items from the list. This is useful when dealing with lists of objects of which you are only really interested in a certain value. The basic usage is mapping on an attribute. Alternatively, you can let it invoke a filter by giving map the parameter name of the filter and the arguments afterward. See map()
in category Filters that generate subsets from Iterables.
{# set myDictList to a list of dictionaries #}
{% set myDictList = [ {'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6} ] %}
{# output the attribute a of values from myDictList #}
{{ myDictList | map(attribute='a') | list }}
Output: [1, 3, 5]
Filters that generate subsets from Iterables
map(filter)
Parameters: Filter any of the filter
Output: Any values from the list processed one by one by the supplied filter
Applies a filter on a sequence of objects. This is useful when you want to process the values of a list. The basic usage is mapping on an attribute. The Map filter is necessary for applying a filter to all members of a List. If, for instance, you tried to apply the upper
filter on a List without the map filter, the upper filter would convert the List to a String and upper the String. Alternatively, you can let it apply a filter on a sequence of objects or looks up an attribute. See map()
in category Filters that modify the content of Iterables.
reject(test, *testArgs)
Paremeters: Test any test, Args arguments for the test
Output: Iterable the iterable with only the items that fail the given test
Filters an Iterable by applying a test to each item, and rejecting the items where the test succeeds. If no test is specified, each object will be evaluated as a boolean.
{# Initialise myList #}
{% set myList = [1,3,4,9,16, 48] %}
{# Print the values from myList not divisible by 3 #}
{{ myList | reject("divisibleby", 3) | list }}
Output: prints [1, 4, 16]
rejectattr(attribute, test, *testArgs)
Parameters: String attribute, Test any test, testArgs the arguments for the test
Output: the supplied iterable without values that match the supplied attribute and succeed the test
Filters an Iterable by applying a test to the specified attribute of each item, and rejecting the items where the test succeeds. If no test is specified, the attribute’s value will be evaluated as a boolean.
{# Initalise myDict #}
{% set myDict = ({'a': 0}, {'a': 1}, {'a': 2}) %}
{# output myDict without the values with key 'a' that are equal to 1.#}
{{ myDict | rejectattr('a', 'equalto', 1) | list }}
Output: [{'a': 0}, {'a': 2}]
select(test, *testArgs)
Paremeters: Test any test, Args arguments for the test
Output: Iterable the iterable with only the items that succeed the given test
Opposite of reject filter. Filters an Iterable by applying a test to each item, and only selecting the items where the test succeeds.If no test is specified, each object will be evaluated as a boolean.
{#Initialise myTuple #}
{% set myTuple = (1, 2, 3, 4, 5) %}
{# output the values from myTuple that are equal to 3 as a list #}
{{ myTuple | select('equalto', 3) | list }}
Output: [3]
selectattr(attribute, test, *testArgs)
Parameters: String attribute, Test any test, testArgs the arguments for the test
Output: the supplied iterable only with the items that match the supplied attribute and succeed the test
Filters an Iterable by applying a test to the specified attribute of each item, and only selecting the items where the test succeeds. If no test is specified, the attribute’s value will be evaluated as a boolean.
{# Initialise myDict #}
{% set myDict = ({'a': 0}, {'a': 1}, {'b': 2}) %}
{# Output only the values from my dict such that they have the attribute a and are equal to 1 #}
{{ myDict | selectattr('a', 'equalto', 1) | list }}
Output: [{'a': 1}]
unique(value)
Parameters: Iterable any iterable
Output: All of the unique items from the given iterable
Returns a list of unique items from the given iterable. The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter.
Filters that modify the order of Iterables
reverse(value)
Parameters: Iterable any iterable
Output: The iterable with item order reversed, or an iterator that iterates from the last item to the first one.
Reverses an Iterable or returns an iterator that iterates over it the other way round.
shuffle(value)
Parameters: Iterable any iterable
Output: Randomly reordered iterable
Randomly reorders the content of an Iterable. If used on Tuples, returns shuffled List. If used on Dictionaries, returns shuffled List of keys.
sort(value, reverse=False, case_sensitive=False, attribute=None)
Parameters: Iterable any iterable, Optional Boolean case_sensitive, String attribute
Output: the given iterable sorted in ascending order.
Sorts an Iterable. Per default it sorts ascending, if you pass it reverse=True it will reverse the sorting, hence it will sort descendingly. If the iterable is made of strings the case_sensitive parameter can be used to control the case sensitiveness of the comparison. It is also possible to sort by an attribute (for example to sort by the date of an object) by specifying the attribute parameter.
Data type filters
You can also use filters to change data types.
Filters that cast variables to different data type
float(value, default=0.0)
Parameters: Any value, Optional Float default the default value
Output: the given Number cast to the type Float
Converts the value into a floatingpoint Number. If the conversion doesn’t work it will return 0.0. Optionally, you can override this default by specifying the default parameter. The float filter can be also used to create inf, inf or nan Numbers by applying float filter to 'inf', 'inf' and 'nan' respectively.
int(value, default=0, base=10)
Parameters: Any value, Optional Integer default, Optional Integer base.
Output: the supplied value as a Number in base 10.
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. Optionally, you can specify the base of the supplied value in the second parameter, 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 nonstring values.
{# Initialise x to the binary value 100 #}
{% set x = "0b100" %}
{# Return x by casting it to base 10 from base 2 #}
{{ x | int(base =2 ) }}
Output: 4
string(value)
Parameters Any value.
Output: the input value converted to Unicode string.
Converts a value to a Unicode string if it isn’t already. That way a markup string is not converted back to Unicode.
list(value)
Parameters: Iterable any iterable
Output: the given iterable as a list
Converts an Iterable into a List. If it is a String the returned list will be a list of characters. Converts Dictionaries to List of keys Note that casting items to List does NOT wrap the items in a List {'a': 1} | list != [{'a': 1}]
but {'a':1} | list == ['a']
safe(value)
Parameters: Any value
Output: the given value marked as safe
Marks the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped. However, Bloomreach Engagement's Jinja does NOT support automatic escaping, so there is no need to mark items as safe.
Filters that transform data between different types
default(value, default_value='', boolean=False)
or d()
Parameters: Any value, Any default_value, Boolean indicating whether None and empty string count as undefined
Output: The supplied value if it is defined, otherwise the default value
If the value is undefined it will return the passed default value, otherwise the value of the variable. This will output the value of my_variable if the variable was defined, otherwise 'my_variable is not defined'. If you want to use the default with variables that evaluate to false you have to set the second parameter to true.
dictsort(value, case_sensitive=False, by='key')
Parameters: Dict dictionary, Boolean case_sensisitve, String by, Boolean reverse
Output: the supplied dictionary sorted by either keys or values as a list of pairs.
Sorts a dictionary and return List of Tuples of (key, value) pairs. Because python dictionaries are unsorted you may want to use this function to order them by either key or value. by argument can be either 'key' or 'value'.
filesizeformat(value, binary=False)
Parameters: Number value, Boolean binary
Output: the supplied value transformed into humanreadable file size format.
Formats the value into a String of a ‘humanreadable’ file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default, decimal prefixes are used (Mega 10ˆ6, Giga 10ˆ9, etc.), if the second parameter is set to True the binary prefixes are used (Mebi 2ˆ20, Gibi 2ˆ30).
from_json(value)
Parameters: JSON String value,
Output: A dictionary that represents the supplied Json
Returns a Dictionary which is the representation of the passed JSON.
The from_json filter carries out the following modifications:
Strings are transformed into a Dictionary of nested objects, to reflect the JSON structure.
Null is turned into none constant.
Boolean True/False are turned into true/false constants
Strings surrounded by doublequotes are transformed into Unicode Strings.
join(value, d='', attribute=None)
Parameters: Iterable any iterable, String d separator, String attribute.
Output: String which is the concatenation of items in the supplied iterable.
Returns a String which is the concatenation of the items in the Iterable. The separator between elements is an empty string per default, you can define it with the optional parameter d.
It is also possible to join certain attributes of an object, e.g. {{ users|join(', ', attribute='username') }}
will output the users joined by username.
json(value)
Parameters: Any value
Output: a string which is the JSON representation of passed argument.
json filter carries out the following modifications:
Tuples are turned into arrays
None is turned into null
Functions (macros, filters, tests) and methods are converted to null.
All keys are converted to Strings and surrounded by doublequotes. Hence, the keys are converted as follows:
Number keys, e.g. 12, is converted to String, e.g. "12"
Boolean constants, e.g. true, is converted to String, e.g. "true"
None constants, e.g. none, is converted to null, and only then to String, so "null"
Although in Jinja, true and false are interchangeable for 1 and 0, true and false parsed by json filter is turned into boolean True and False, while 1 and 0 are turned into Numbers 1 and 0.
length(object)
or count()
Parameters: Iterable any iterable.
Output: the Number of items in an iterable.
Returns an Integer, Number of items in an Iterable.
sum(iterable, attribute=None, start=0)
Parameters: Iterable any iterable, Optional String attribute, Optional Integer start
Output: Sum of a sequence of Numbers plus the value given by parameter start
Returns the sum of a sequence of Numbers plus the value of the parameter ‘start’ (which defaults to 0). When the sequence is empty it returns the value of start parameter. It is also possible to only sum up certain attributes: {{ items|sum(attribute='price') }}
.
wordcount(String)
Parameters: String value
Output: the Number of words in the given string.
Counts the words in that string. Words are defined as characters separated by whitespace.
xmlattr( Dictionary, autospace=True)
Parameters: Dictionary any dictionary, Boolean autospace
Output: String that represents the SGML/XML attribute
Creates an SGML/XML attribute String based on the items in a dictionary. All values that are neither none nor undefined are automatically escaped:
{# Initialise myDict #}
{% set myDict = {'a': 0, 'b': '<cool>'} %}
{# return the xml attribute string from dict #}
{{ myDict | xmlattr }}
Output: 'a="0" b="<cool>"'
Date & time processing
from_timestamp(value, [formatter])
Parameters: Number value Unix timestamp, Optional String formatter format string
Output: Unix timestamp formatted to a datetime object or human readable string.
With no formatter parameter supplied, converts the Unix timestamp (Number) to a date time object that can be either directly printed or further processed, as you can see in these examples.
{% set a = 1577865600 | from_timestamp %}
{{ a }}
Output: 2020-01-01 08:00:00+00:00
{{ a.year }} {{ a.month }} {{ a.day }}
Output: 2020 1 1
{{ a.hour }} {{ a.minute }} {{ a.second }}
Output: 8 0 0
date {{ a.date() }} time {{ a.time() }}
Output: date 2020-01-01 time 08:00:00
{# 0 is Monday, 2 is Wednessday, 6 is Sunday #}
{{ a.weekday() }}
Output: 2
{# You can also overwrite the year/month/day/hour/minute/second #}
{% set b = a.replace(day=2, hour=16) %}
{{ b }}
Output: 2020-01-02 16:00:00+00:00
{{ b.timestamp() }}
1577980800.0
The optional argument formatter can be 'US' or 'EU' for common datetime formats, or a custom datetime format string. The format string can contain formatting codes ('%' + char) that are replaced with time values (see the table below for all available time values).
{{ 1579204800 | from_timestamp('US') }}
Output: 01/16/2020, 08:00 PM
{{ 1579204800 | from_timestamp('EU') }}
Output: 16-01-2020, 20:00
{{ 1579204800 | from_timestamp('%A %d of %B %Y') }}
Output: Thursday 16 of January 2020
Code | Description | Output example |
%y
|
Year without century as a zeropadded decimal Number. | 13
|
%Y
|
Year with century as a decimal Number. | 2013
|
%A
|
Weekday as locale’s full name. | Monday
|
%a
|
Weekday as locale’s abbreviated name. | Mon
|
%w
|
Weekday as a decimal Number, where 0 is Sunday and 6 is Saturday. | 1
|
%U
|
Week Number of the year (Sunday as the first day of the week) as a zero padded decimal Number.
All days in a new year preceding the first Sunday are considered to be in week 0. |
39
|
%W
|
Week Number of the year (Monday as the first day of the week) as a decimal Number.
All days in a new year preceding the first Monday are considered to be in week 0. |
39
|
%z
|
UTC offset in the form +HHMM or HHMM (empty string if the the object is naive). | +0100
|
%S
|
Second as a zeropadded decimal Number. | 05
|
%-S
|
Second as a decimal Number. (Platform specific) | 5
|
%-d
|
Day of the month as a decimal number. (Platform specific) | 9
|
%B
|
Month as locale’s full name. | September
|
%b
|
Month as locale’s abbreviated name. | Sep
|
%-m
|
Month as a decimal Number. (Platform specific) | 9
|
%M
|
Minute as a zeropadded decimal Number. | 06
|
%-M
|
Minute as a decimal Number. (Platform specific) | 6
|
%f
|
Microsecond as a decimal Number, zeropadded on the left. | 000000
|
%p
|
Locale’s equivalent of either AM or PM. | AM
|
%X
|
Locale’s appropriate time representation. | 07:06:05
|
%x
|
Locale’s appropriate date representation. | 09/30/13
|
%c
|
Locale’s appropriate date and time representation. | Mon Sep 30 07:06:05 2013
|
%H
|
Hour (24hour clock) as a zeropadded decimal Number. | 07
|
%-H
|
Hour (24hour clock) as a decimal Number. (Platform specific) | 7
|
%-I
|
Hour (12hour clock) as a decimal Number. (Platform specific) | 7
|
%j
|
Day of the year as a zeropadded decimal Number. | 273
|
%-j
|
Day of the year as a decimal Number. (Platform specific) | 273
|
%%
|
A literal '%' character. | %
|
When using Jinja filters like {% set variable=(input+offset)|from_timestamp('%w')%}, the output may not always be a decimal number as might be expected, even if the filter typically outputs a number. In certain contexts, it might output a string instead. To ensure that the output is handled as a number, you can convert it using the "|int" filter like this: {% set variable=(input+offset)|from_timestamp('%w') | int %}.
to_timestamp(datetime_string, [format], [timezone])
Parameters: datetime_string, Optional String format, Optional String timezone
Output: Number Unix timestamp (seconds since 1970).
Parses a date & time string to a Unix timestamp. Can optionally use a format string described in from_timestamp, defaulting to a smart guess from among common date & time formats. Can optionally accept a tz DB timezone name to specify the timezone of the string representation, defaulting to UTC.
{{ '2020-01-20 20:20:20.20' | to_timestamp }}
Output: 1579551620.2
{{ '25/02/2020' | to_timestamp('%d/%m/%Y', timezone='America/New_York') | int }}
Output: 1582606800
Updated 8 months ago