from jinja2 import Template
d = {'e34': ['120'], 'e24': ['50']}
s = """{% set result = 'default' %}
{% for item, value in test_dict.items() %}
{% if 'e2' in item %}
{% set result = item %}
{{ result }}
{% endif %}
{% endfor %}"""
template = Template(s)
print(template.render(test_dict=d))
jinja2使用了^{} 和Python3类似,而是使用了^{} 格式的Python2,如docs中所述。在
另外,您需要使用
set
将变量result
转换为字典中的item
:因为我在我的系统上使用Python3,所以我不得不调用
.items()
。根据您的版本,您可以改为调用.iteritems()
。在因为我的系统上没有设置jinja2沙盒环境,所以我不得不编写一个快速而肮脏的代码片段,如上图所示。这将产生以下输出:
^{pr2}$从光学角度来说,这不是很好,但它打印出所需的
e24
。在相关问题 更多 >
编程相关推荐