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:

Custom Locoia variables

All custom Locoia variables, wildcards, and functions can be found here.

Additional details

For some functions there're additional details to consider.

regex_replace

In order to capture groups with this function \g<name> needs to be used with named groups and \g<number> with plain groups.

Noteworthy core Jinja functions

selectattr

  • 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

namespace()

  • 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 carried across 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 %}    
]

get()

The get() function in Jinja (a standard Python dictionary method) allows you to efficiently map a dictionary using key-value pairs. It is particularly useful when dealing with scenarios where you need to map values based on specific keys.

  • Example Imagine you have to map a dictionary with the following key-value pairs:

{% set type_mapping = 
  {
    'Wohnung': 'APARTMENT', 
    'Stellplatz außen': 'PARKING', 
    'Garagen': 'PARKING'
  } 
%}

Traditionally, you might use an if-else statement to perform the mapping:

{% if unit_type in type_mapping %}
  "{{ type_mapping[unit_type] }}"
{% else %}
  "DEFAULT VALUE"
{% endif %}

However, to minimize code and enhance readability, you can achieve the same result using the get() function:

{{ type_mapping.get(unit_type, "DEFAULT VALUE") }}

The get() function retrieves the value associated with the specified unit_type from the dictionary. If the unit_type is not found, it defaults to the specified "DEFAULT VALUE". This approach simplifies the code and improves maintainability.

Last updated