遍历神社数组
Iterate over jinja array
我有以下神社数组:
{'e34': ['120'], 'e24': ['50']}
我想查找一个单词是否包含e2
,并将其带到另一个函数中。
我做了以下事情:
{% set result = 'default' %}
{% for item, value in jinjaarray.items() %}
{% if 'e2' in item %}
result = item
{% endif %}
{% endfor %}
但是失败了,没有进入循环
我该怎么做?
改为使用 .items()
like Python3, jinja2 uses Python2-fashioned .iteritems()
as stated in the docs.
此外,您需要使用 set
:
将字典中的变量 result
result
item
assign
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))
因为我在我的系统上使用 Python3,所以我不得不调用 .items()
。根据您的版本,您可能会调用 .iteritems()
。
因为我没有在我的系统上设置 jinja2 沙盒环境,所以我不得不编写一个快速而肮脏的代码片段,如上所示。这将提供以下输出:
'\n\n \n \n e24\n \n\n \n'
从视觉上讲这不是很好,但它打印出 e24
的期望值。
我有以下神社数组:
{'e34': ['120'], 'e24': ['50']}
我想查找一个单词是否包含e2
,并将其带到另一个函数中。
我做了以下事情:
{% set result = 'default' %}
{% for item, value in jinjaarray.items() %}
{% if 'e2' in item %}
result = item
{% endif %}
{% endfor %}
但是失败了,没有进入循环
我该怎么做?
改为使用 .items()
like Python3, jinja2 uses Python2-fashioned .iteritems()
as stated in the docs.
此外,您需要使用 set
:
result
result
item
assign
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))
因为我在我的系统上使用 Python3,所以我不得不调用 .items()
。根据您的版本,您可能会调用 .iteritems()
。
因为我没有在我的系统上设置 jinja2 沙盒环境,所以我不得不编写一个快速而肮脏的代码片段,如上所示。这将提供以下输出:
'\n\n \n \n e24\n \n\n \n'
从视觉上讲这不是很好,但它打印出 e24
的期望值。