如何在Jinja2模板中连接int和str类型?

21

我希望在jinja2模板中设置一个变量,它是字符串和整数值的组合。

代码如下:

{% set the_var = 'Wan_Links.WAN_' + i + '.wan_link_type' %}

"i"是一个动态值,类型为int。当我运行上面的代码时,我会得到以下错误:TypeError: cannot concatenate 'str' and 'int' objects

预期输出为the_var = Wan_Links.WAN_0.wan_link_type(即i = 0)。请问有人能告诉我如何做到这一点吗?

2个回答

32

还可以使用~运算符:

~将所有操作数转换为字符串并将它们连接起来。 {{ "Hello " ~ name ~ "!" }} 会返回(假设name的值为'John'):Hello John!

http://jinja.pocoo.org/docs/2.10/templates/


22

通过添加 "String" 来完成它。 正确的语法是:

{% set the_var = 'Wan_Links.WAN_' + i|string + '.wan_link_type' %}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接