Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store result of Jinja filter

Tags:

set

jinja2

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.

like image 572
RHollister Avatar asked Nov 30 '11 16:11

RHollister


2 Answers

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.

like image 88
Garrett Avatar answered Nov 11 '22 08:11

Garrett


| in Jinja just passes the variable into the function. Simply call the function and it should work:

{% set image = random(images) %}
like image 30
Sean Vieira Avatar answered Nov 11 '22 10:11

Sean Vieira