List of Jinja Filters
Last updated
Last updated
Feedback
⬆️ CannyCopyright © 2024 Rewst
to organize your data. In any Jinja editor on the platform, you can see what's available by using the |
character within {{ }}
Here is everything available:
Function | Description |
---|---|
| Return the absolute value of the argument. |
| Return |
| Return :py:data:False if none of the elements of the (async) iterable are true. |
| Return a string representation of a datetime in a particular format.
|
| Get an attribute of an object. foo |
| Encode a string in base64.
|
| A filter to get the last name of a windows style file path. |
| A filter that batches items. It works pretty much like slice but the other way round. 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. |
| Capitalize a value. The first character will be uppercase, all others lowercase. |
| Centers the value in a field of a given width. |
| Based on the Ansible combine filter, this filter allows hashes to be merged. For example, the following would override keys in one hash:
Parameters:
Other examples:
|
| Convert an epoch timestamp to a datetime object
|
| Return the number of items in a container. |
| Dump a list of rows (as dicts, or lists) to CSV format
|
| 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 default with variables that evaluate to false you have to set the second parameter to true.
|
| Add or subtract a number of years, months, weeks, or days from a datetime
|
| 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 default with variables that evaluate to false you have to set the second parameter to true.
|
| This filter transforms lists into dictionaries. |
| Sort a dict and yield (key, value) pairs. Python dicts may not be in the order you want to display them in, so sort them first. |
| To get the directory from a path. |
| 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.
|
| An async iterator of running count and element in an (async) iterable The count begins at start for the first element of iterable, and is incremented by 1 for each further element. The iterable may be a regular or async iterable. |
| 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.
|
| Format the value like a 'human-readable' file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega, Giga, etc.), if the second parameter is set to True the binary prefixes are used (Mebi, Gibi). |
| Return the first item of a sequence. |
| Flatten a list of lists.
|
| 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 first parameter. |
| Enforce HTML escaping. This will probably double escape variables. |
| Apply the given values to a printf-style_ format string, like string % values. In most cases, it should be more convenient and efficient to use the % operator or :meth:str.format. _printf-style: https://docs.python.org/library/stdtypes.html |
| Return a string representation of a datetime in a particular format.
|
| Deserialize from a JSON-serialized string |
| Deserialize from a YAML-serialized string |
| Group a sequence of objects by an attribute using Python's :func:itertools.groupby. 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.
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.
You can specify a default value to use if an object in the list does not have the given attribute.
Like the :func:~jinja-filters.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.
|
| Return the bytes digest of the HMAC. Usage: or returns
|
| Returns hex representations of bytes objects and UTF-8 strings.
Usage:
|
| Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default.
|
| 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. You can also override the default base (10) 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 non-string values. |
| Determines whether or not a string can be converted to a JSON object. |
| Checks the type of the object the filter is being applied to, parameter supplied is for the type to check for.
This returns a boolean value.
Example:
|
| Return an iterator over the (key, value) items of a mapping. |
| 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.
It is also possible to join certain attributes of an object.
|
| Parse a JSON-serialized string |
| Serialize value to JSON |
| Add escape sequences to problematic characters in the string
This filter simply passes the value to |
| Deserialize from a JSON-serialized string |
| Serialize value to JSON |
| Extracts data from an object value using a JSONPath query. 🔗 https://github.com/h2non/jsonpath-ng |
| Return the last item of a sequence. Note: Does not work with generators. You may want to explicitly convert it to a list. |
| Return the number of items in a container. |
| Create a :py:class:list from an (async) iterable. This is equivalent to [element async for element in iterable]. |
| Parse a datetime string with a known format specification.
|
| Convert a value to lowercase. |
| Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list of users but you are only interested in a list of usernames:
You can specify a default value to use if an object in the list does not have the given attribute.
Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good example would be applying a text conversion filter on a sequence:
Similar to a generator comprehension such as:
|
| Return the largest item from an (async) iterable or from two or more values :raises ValueError: if iterable is empty and default is not set The key argument specifies a one-argument ordering function like that used for :py:meth:list.sort. It may be a regular or async callable and defaults to the identity function. The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a :py:exc:ValueError is raised. |
| Return the smallest item from an (async) iterable or from two or more values :raises ValueError: if iterable is empty and default is not set The key argument specifies a one-argument ordering function like that used for :py:meth:list.sort. It may be a regular or async callable and defaults to the identity function. The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a :py:exc:ValueError is raised. |
| Parse a CSV string into a list of dicts, with column headers as keys
A list of list of strings (i.e. a collection of rows, each row containing column values) may be passed instead of a CSV.
|
| Parse a datetime string without knowing its format specification.
This method of parsing is more lenient than load_datetime
|
| Pretty print a variable. Useful for debugging. |
| Return a random item from the sequence. |
| Reduce an (async) iterable by cumulative application of an (async) function. :raises TypeError: if iterable is empty and initial is not given Applies the function from the beginning of iterable, as if executing await function(current, anext(iterable)) until iterable is exhausted. Note that the output of function should be valid as its first input. The optional initial is prepended to all items of iterable when applying function. If the combination of initial and iterable contains exactly one item, it is returned without calling function. |
| To occurrences of regex matches in a string, use the regex_findall filter. |
| This function is used to determine if a string matches a particular pattern. It takes three parameters:
* |
| To replace text in a string with regex, use the regex_replace filter. |
| To search in a string with a regular expression and detect matches within a string, use the regex_search filter. It will return a boolean (true/false) if the defined regex exists within the string. |
| This function is used to find all the substrings in a string that match a particular pattern and return the substring at a specific index. It takes four parameters:
* |
| Filters a sequence of objects by applying a test to each object, and rejecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
|
| Filters a sequence of objects by applying a test to the specified attribute of each object, and rejecting the objects with the test succeeding.
If no test is specified, the attribute's value will be evaluated as a boolean.
Similar to a generator comprehension such as:
|
| 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. If the optional third argument count is given, only the first count occurrences are replaced. |
| Reverse the object or return an iterator that iterates over it the other way round. |
| Round the number to a given precision. The first parameter specifies the precision (default is 0), the second the rounding method:
* |
| Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped. |
| Filters a sequence of objects by applying a test to each object, and only selecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
Similar to a generator comprehension such as:
|
| Filters a sequence of objects by applying a test to the specified attribute of each object, and only selecting the objects with the test succeeding.
If no test is specified, the attribute's value will be evaluated as a boolean.
Similar to a generator comprehension such as:
|
| Create a :py:class:set from an (async) iterable This is equivalent to {element async for element in iterable}. |
| Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns: .. sourcecode:: html+jinja If you pass it a second argument it's used to fill missing values on the last iteration. |
| Sort an iterable using Python's :func:sorted.:param reverse: Sort descending instead of ascending. :param case_sensitive: When sorting strings, sort upper and lower case separately. :param attribute: When sorting objects or dicts, an attribute or key to sort by. Can use dot notation like "address.city". Can be a list of attributes like "age,name". 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. <div data-gb-custom-block data-tag="for" data-0=') |
| Convert an object to a string if it isn't already. This preserves a :class: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.
|
| Strip SGML/XML tags and replace adjacent whitespace by one space. |
| Returns the sum of a sequence of numbers plus the value of parameter 'start' (which defaults to 0). When the sequence is empty it returns start. It is also possible to sum up only certain attributes: .. versionchanged:: 2.6 The attribute parameter was added to allow summing up over attributes. Also the start parameter was moved on to the right. |
| Add a duration of time to a datetime Use negative values to subtract durations of time instead. |
| Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase. |
| Transliterate a Unicode object into an ASCII string errors specifies what to do with characters that have not been found in replacement tables. The default is 'ignore' which ignores the character. 'strict' raises an UnidecodeError. 'replace' substitutes the character with replace_str (default is '?'). 'preserve' keeps the original character. Note that if 'preserve' is used the returned string might not be ASCII! |
| Given a time value in seconds, this function returns a fuzzy version like 3m5s. :param seconds: Time specified in seconds. :type seconds: int or long or float :rtype: str |
| Serialize value to JSON |
| Serialize to YAML :param indent: Number of spaces to use for indentation :param sort_keys: Whether to sort mapping keys, or leave as-is |
| Serialize an object to a string of JSON, and mark it safe to render in HTML. This filter is only for use in HTML documents.
The returned string is safe to render in HTML documents and |
| Strip leading and trailing characters, by default whitespace. |
| Return a truncated copy of the string. The length is specified with the first parameter which defaults to 255. If the second parameter is true the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign ("..."). If you want a different ellipsis sign than "..." you can specify it using the third parameter. Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated. The default leeway on newer Jinja versions is 5 and was 0 before but can be reconfigured globally. |
| Create a :py:class:tuple from an (async) iterable |
| Transliterate a Unicode object into an ASCII string errors specifies what to do with characters that have not been found in replacement tables. The default is 'ignore' which ignores the character. 'strict' raises an UnidecodeError. 'replace' substitutes the character with replace_str (default is '?'). 'preserve' keeps the original character. Note that if 'preserve' is used the returned string might not be ASCII! |
| 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. :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Filter objects with unique values for this attribute. |
| Convert a value to uppercase. |
| Quote data for use in a URL path or query using UTF-8. Basic wrapper around :func:urllib.parse.quote when given a string, or :func:urllib.parse.urlencode for a dict or iterable. :param value: Data to quote. A string will be quoted directly. A dict or iterable of (key, value) pairs will be joined as a query string. When given a string, "/" is not quoted. HTTP servers treat "/" and "%2F" equivalently in paths. |
| Convert URLs in text into clickable links.
This may not recognize links in some situations. Usually, a more comprehensive formatter, such as a Markdown library, is a better choice.
Works on |
| Convert a None value to a magic string preserving the None value when passed to actions |
| This function increments the major version component of a version number ( |
| This function increments the minor version component of a version number ( |
| This function increments the patch version component of a version number ( |
| This function compares two version numbers ( |
| This function compares two version numbers ( |
| This function compares two version numbers ( |
| This function checks if a version number ( |
| This function compares two version numbers ( |
| This function removes the patch version component from a version number ( |
| Count the words in that string. |
| Wrap a string to the given width. Existing newlines are treated as paragraphs to be wrapped separately. :param s: Original text to wrap. :param width: Maximum length of wrapped lines. :param break_long_words: If a word is longer than width, break it across lines. :param break_on_hyphens: If a word contains hyphens, it may be split across lines. :param wrapstring: String to join each wrapped line. Defaults to :attr:Environment.newline_sequence. .. versionchanged:: 2.11 Existing newlines are treated as paragraphs wrapped separately. .. versionchanged:: 2.11 Added the break_on_hyphens parameter. .. version changed:: 2.7 Added the wrapstring parameter. |
| Take a text string and wrap it to a specified width. The resulting string will be the original text except with newlines inserted so that no line is wider than the specified width. The default width is 70 characters. Raises: TypeError: If text is not a string TypeError: If width is not an integer wrap_text('Vero aliquam debitis. Reiciendis commodi dol', width=20) 'Vero aliquam\ndebitis. Reiciendis\ncommodi dol' |
| Create an SGML/XML attribute string based on the items in a dict. All values that are neither none nor undefined are automatically escaped: .. sourcecode:: html+jinja Results in something like this: .. sourcecode:: html As you can see it automatically prepends a space in front of the item if the filter returned something unless the second parameter is false. |
| Serialize to YAML :param indent: Number of spaces to use for indentation :param sort_keys: Whether to sort mapping keys, or leave as-is |
| Deserialize from a YAML-serialized string |
| Return a list of tuples where the i-th element comes from the i-th list arg. If a list is exhausted before the others, the value of pad will be used in the tuple. |