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

Custom Locoia variables can be found in the Functions Reference Panel in the Flow Builder and via autocomplete:

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:

  • 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.

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:

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

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

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

Was this helpful?