Abh*_*jit 16 python templates jinja2
我想在 jinja2 模板中设置一个变量,它是字符串和整数值的组合。
代码如下:
{% set the_var = 'Wan_Links.WAN_' + i + '.wan_link_type' %}
Run Code Online (Sandbox Code Playgroud)
这里的“i”是一个动态值,类型为 int。当我运行上面的代码时,我收到以下错误: TypeError: cannot concatenate 'str' and 'int' objects。
预期的输出是the_var = Wan_Links.WAN_0.wan_link_type(即 i=0)。谁能告诉我如何完成这项工作?
dmo*_*ock 25
您还可以使用~运算符:
~将所有操作数转换为字符串并连接它们。{{ "Hello " ~ name ~ "!" }}将返回(假设 name 设置为 'John'):Hello John!。
http://jinja.pocoo.org/docs/2.10/templates/
Abh*_*jit 18
通过向它添加“字符串”来完成。正确的语法是:
{% set the_var = 'Wan_Links.WAN_' + i|string + '.wan_link_type' %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13505 次 |
| 最近记录: |