How to update a global variable from inside an IF/ELSE statement or FOR loop in JINJA

JINJA2 has a limitation that prevents changing a global variable from inside an IF/ELSE statement of FOR loop. 

 

Example scenario (not working):

In this code, we want to change the variable hasDiscount from inside the IF/ELSE statement, depending on whether the user has any vouchers in their vouchers list user attribute. Unfortunately, it won't work:

{% set hasDiscount = FALSE %}

{% if userAttribute.vouchers %}
{% set hasDiscount = TRUE %}
{% endif %}

{{hasDiscount}} <---- still prints FALSE

 

Workaround:

Appending values to a global list variable works from inside the scope of IF/ELSe or FOR statements. We can make hasDiscount an empty list and append values to it as needed. Example:

{% set hasDiscount = [] %}

{% if userAttribute.vouchers %}
{% set temp = hasDiscount.append(TRUE) %}
{% endif %}

Printing all items from the hasDiscount list:
{% for item in hasDiscount %}
{{item}}
{% endfor %}

Or just printing the first item:
{{hasDiscount[0]}}

Was this article helpful?
Have more questions? Submit a request