283
votes

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.

3
Folks landing here from Google: you will probably be primarily interested in the official docs on the set tag, rather than the specific syntax mistake made by the asker here or how to fix it, which is what the top answers here and at the linked duplicate address.Mark Amery
@MarkAmery Ty! Especially this part jinja.palletsprojects.com/en/2.11.x/templates/… is extremely helpful.ruohola

3 Answers

568
votes

{{ }} 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
65
votes

Nice shorthand for Multiple variable assignments

{% set label_cls, field_cls = "col-md-7", "col-md-3" %}
26
votes

Just Set it up like this

{% set active_link = recordtype -%}