[英]Jinja2 Iterate over dictionary that contains list of dictionaries template error
I have a Python object that looks like this coming from flask:我有一个 Python object 看起来像这样来自 flask:
data = {
"sunday": [{"key":"value"}],
"monday" : [{"key":"value"}],
"tuesday": [{"key":"value"}],
"wednesday": [{"key":"value"}],
"thursday": [{"key":"value"}],
"friday": [{"key":"value"}],
"saturday": [{"key":"value"}]
}
In my HTML file, I've tried the following:在我的 HTML 文件中,我尝试了以下操作:
// #1
{% for key, value in data.items %}
{% for item in value %}
<p>{{item.key}}</p>
{% endfor %}
{% endfor %}
// #2
{% for key, value in data.items() %}
{% for item in value %}
<p>{{item.key}}</p>
{% endfor %}
{% endfor %}
// #3
{% for key, value in data.items %}
{% endfor %}
// #4
{% for key, value in data.items() %}
{% endfor %}
All of these return the same error:所有这些都返回相同的错误:
jinja2.exceptions.TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.
The only thing that works is:唯一有效的是:
{% for key in data %}
{% endfor %}
But this returns nothing and I can't iterate further.但这没有返回任何内容,我无法进一步迭代。 How can I iterate over my dictionary that contains lists of dictionaries and print out values?
如何遍历包含字典列表的字典并打印出值?
You're missing a third loop:你错过了第三个循环:
data = {
"sunday": [{"key":"value"}],
"monday" : [{"key":"value"}],
"tuesday": [{"key":"value"}],
"wednesday": [{"key":"value"}],
"thursday": [{"key":"value"}],
"friday": [{"key":"value"}],
"saturday": [{"key":"value"}]
}
data
is a dictionary, each of the values holds a list. data
是一个字典,每个值都有一个列表。 Until here you're right.直到这里你是对的。 But in the list you have another dictionary, which you need to loop over as well:
但是在列表中你有另一个字典,你也需要循环它:
{% for key, val in data.items() %}
{% for entry in val %}
{# You could also access item 0 if you know for a #}
{# fact that the list always holds a single entry. #}
{% for entry_key, entry_val in entry.items() %}
<p>{{entry_key}}</p>
{% endfor %}
{% endfor %}
{% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.