jinja2 - 使用 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'
解决方案
'my_string_'
只是一个字符串,而不是一个变量。由于您的“变量”名称只是用递增数字命名,因此您应该将其设为列表:
outputText = template.render(my_array=['test with 0', 'test with 1'])
因此您可以遍历模板中的列表:
{% for item in my_array %}
{{ item }}
{% endfor %}
推荐阅读
- c# - 在为 Azure Functions 3.0 添加单例时注入 ILogger
- amazon-web-services - 将图片发送到 aws s3 存储桶时出现 net::ERR_NAME_NOT_RESOLVED 错误
- jquery - Laravel 6 @yield() 在 include() 方法中不起作用
- javascript - SonarQube - 不应使用函数构造函数
- python - 在 Windows 中将目录永久添加到 PYTHONPATH?
- php - 在添加 group_by() codeigniter 时在布尔值上调用成员函数 result()
- c++ - 在 C++ 中解析逗号分隔的整数/整数范围
- python - 在 re 库中使用 findall 时出错
- node.js - 快速解析没有内容类型标头的 JSON
- java - 在 Rest Assured 中,getString() 将 4 位后的十进制值四舍五入