Set variable in jinja
PythonTemplatesVariablesVariable AssignmentJinja2Python Problem Overview
I would like to know how can I set a variable with another variable in jinja. I will explain, I have got a submenu and I would like show which link is active. I tried this:
{% set active_link = {{recordtype}} -%}
where recordtype is a variable given for my template.
Python Solutions
Solution 1 - Python
{{ }}
tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %}
template tag and then assign the value the same way you would in normal python code.
{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}
Result:
it worked
Solution 2 - Python
Nice shorthand for Multiple variable assignments
{% set label_cls, field_cls = "col-md-7", "col-md-3" %}
Solution 3 - Python
Just Set it up like this
{% set active_link = recordtype -%}
Solution 4 - Python
You can do this with the set
tag. See the official documentation.
For example,
{% set foo = "bar" %}
{{ foo }}
outputs
bar
Note: there are scoping issues which means that variable values don’t persist between loop iterations, for example, if you want some output to be conditional on a comparison between previous and current loop values:
{# **DOES NOT WORK AS INTENDED** #}
{% set prev = 0 %}
{% for x in [1, 2, 3, 5] %}
{%- if prev != x - 1 %}⋮ (prev was {{ prev }})
{% endif -%}
{{ x }}
{%- set prev = x %}
{% endfor %}
prints
1
⋮ (prev was 0)
2
⋮ (prev was 0)
3
⋮ (prev was 0)
5
because the variable isn’t persisted. Instead you can use a mutable namespace wrapper:
{% set ns = namespace(prev=0) %}
{% for x in [1, 2, 3, 5] %}
{%- if ns.prev != x - 1 %}⋮ (ns.prev was {{ ns.prev }})
{% endif -%}
{{ x }}
{%- set ns.prev = x %}
{% endfor %}
which prints
1
2
3
⋮ (ns.prev was 3)
5
as intended.