Python 在 jinja 中设置变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3727045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:26:19  来源:igfitidea点击:

Set variable in jinja

pythontemplatesvariablesvariable-assignmentjinja2

提问by MyTux

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:

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

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

where recordtype is a variable given for my template.

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

回答by Soviut

{{ }}tells the template to printthe 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 %}模板标记,然后以与在普通 Python 代码中相同的方式分配值。

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

Result:

结果:

it worked

回答by Chad Pierce

Just Set it up like this

就这样设置

{% set active_link = recordtype -%}

回答by pymen

Nice shorthand for Multiple variable assignments

多变量赋值的简写

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