首页 > 解决方案 > 使用 jinja2 连接字符串并进行迭代

问题描述

我想使用字符串的串联和迭代创建一个变量名:

{% for iteration in my_array %}
   {% set my_var = 'my_string_' + loop.index0|string %}
   {{ my_var }}
{% endfor %}

在我的带有数据的python文件中:

templateVars={
    'my_string_0': 'test with 0',
    'my_string_1': 'test with 1'
}
outputText = template.render(templateVars)

但我没有得到 'test with 0' 我得到 'my_string_0'

标签: jinja2

解决方案


'my_string_'只是一个字符串,而不是一个变量。由于您的“变量”名称只是用递增数字命名,因此您应该将其设为列表:

outputText = template.render(my_array=['test with 0', 'test with 1'])

因此您可以遍历模板中的列表:

{% for item in my_array %}
   {{ item }}
{% endfor %}

推荐阅读