setjinja2

Store result of Jinja filter


The basics of what I am trying to do is to use the 'random' filter to choose a random item from my list but then I want to use that randomly chosen item in multiple locations.

How do I set the result of a filter to a variable that I can use in multiple locations.

If I call the 'random' filter multiple times there is little chance they will be the same.

Essentially what I want to do:

{% set image = {{ images | random }} %}

obviously this doesnt work.


Solution

  • Use the filter without {{ }} delimiters.

    {% set image = images|random %}
    

    Jinja stores globals and filters in two different namespaces (dictionaries), which prevents them from being used interchangeably.