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.
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
Using String filters on non-String variables casts the variables to Strings.
## 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)
`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:
`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](🔗)
`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_ break_long_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.
### 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.
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.
`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.
`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.
### 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.
`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.
`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.
`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.
`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.
`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', reverse=False)
`
**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:
## 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.
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).
`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.