Comment on page
Jinja: (Custom) variables, wildcards and functions
Jinja2, one of the world's most popular data rendering engines, is used as a templating language to render individual information. Many core functions are available. Some are not available for security reasons. A list of the core external functions can be found under:
For some functions there're additional details to consider.
In order to capture groups with this function
\g<name>
needs to be used with named groups and \g<number>
with plain groups.- Usage:{% for record in list_reference | selectattr(field_reference, 'match', 'comparison_value') %}
- Use case: This lets you filter any (nested) list directly in Jinja by specific attributes
- Usage: The
namespace
object (container) is an easy way to create an object with attributes. It helps avoid conflicts with variable names and provides a clean and concise way to store and retrieve values within the context of a template.This is particularly useful when carrying a value from within a loop body to outside the loop, which is not possible with standard variables. - Example: This code snippet generates a list of records, separating them with commas. It utilizes a dedicated
comma_set
object to track whether a comma has been set for any record, so that it can be placed correctly for a valid JSON. As this variable value needs to be caried accross loop iterations, a namespace needs to be used.
{% set comma_set = namespace(first_comma_set=False) %}
[
{% for record in records %}
{% if record ... %}
{% if comma_set.first_comma_set %},
{% else %}
{% set comma_set.first_comma_set = True %}
{% endif %}
{{ record }}
{% endif %}
{% endfor %}
]
Last modified 12d ago