在Jinja中设置变量

问题:在Jinja中设置变量

我想知道如何在Jinja中使用另一个变量设置变量。我会解释,我有一个子菜单,我想显示哪个链接处于活动状态。我尝试了这个:

{% set active_link = {{recordtype}} -%}

其中recordtype是为我的模板提供的变量。

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.


回答 0

{{ }}告诉模板打印值,这在您尝试执行的表达式中将不起作用。而是使用{% set %}template标记,然后以与普通python代码相同的方式分配值。

{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}

结果:

it worked

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

回答 1

多个变量分配的不错简写

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

Nice shorthand for Multiple variable assignments

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

回答 2

像这样设置

{% set active_link = recordtype -%}

Just Set it up like this

{% set active_link = recordtype -%}