gpt4 book ai didi

python - 在 html Flask 中迭代嵌套字典时出现 jinja2.exceptions.UndefinedError

转载 作者:行者123 更新时间:2023-12-01 07:03:08 25 4
gpt4 key购买 nike

我有以下字典。

parent_dict= {
"AAA": 19,
"BBB": 74861149,
"CCC": "84%",
"ABC": {
"Types": {
"A1": 25
}
},
"DEF": {
"Average": 279,
"Types": {
"B1": 12,
"B2": 1500,
"B3": 9000
},
"Total": 46248438
}
}

我想在 html 页面中迭代这个嵌套字典。该字典通过 Flask python 中的 render_template 发送。

我使用 python 和 Flask 创建一个端点并将其发送到我的 HTML 页面。

app.py

@app.route('/sendData',methods=['GET','POST'])
def sendData():
return render_template('demo.html', parent_dict=parent_dict)

demo.html

{% for key,parent_dict_item in parent_dict.items() %}
{% for key2, nested_value in parent_dict_item.items() %}
<p>{{ parent_dict_item }}</p>
{% endfor %}
{% endfor %}

当我在 Chrome 中运行该 URL 时收到此错误。

jinja2.exceptions.UndefinedError UndefinedError: 'int object' has no attribute 'items'

如何解决这个问题?

最佳答案

您的嵌套 for 循环假设每个第二级条目也是一个字典,但事实并非如此,它会在第一项上中断:

{% for key,parent_dict_item in parent_dict.items() %}

# key = "AAA", parent_dict_item = 19

{% for key2, nested_value in parent_dict_item.items() %}

# This breaks, because parent_dict_item is 19 (an int) so you can't call int.items().

<p>{{ parent_dict_item }}</p>
{% endfor %}
{% endfor %}

您需要添加条件逻辑来定义当parent_dict_item不是字典时您想要执行的操作。

关于python - 在 html Flask 中迭代嵌套字典时出现 jinja2.exceptions.UndefinedError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58553392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com