【发布时间】:2021-12-08 03:37:41
【问题描述】:
我有一本包含所有国家代码和相应国家名称的字典,它的示例如下所示:
{'AF': 'Afghanistan'}
{'AL': 'Albania'}
{'DZ': 'Algeria'}
{'AD': 'Andorra'}
{'AO': 'Angola'}
当我关注这个堆栈溢出问题时:How to iterate through a list of dictionaries in Jinja template? 尝试遍历国家时我遇到了一个问题,因为它没有添加任何元素。 这是我的代码:
{% extends "base.html" %} {% block title %}Test{% endblock %}
{% block content %}
<div class="container pt-5">
<h1 align="center">TEST PAGE</h1>
</div>
{% for dict_item in countries %}
{% for key,value in dict_item.items %}
<h1>Key: {{ key }}</h1>
<h2>Value: {{ value }}</h2>
{% endfor %}
{% endfor %}
{% endblock %}
它没有添加任何标题,当我尝试dict_items.items()(项目后有括号)时,我收到错误:jinja2.exceptions.UndefinedError: 'str object' has no attribute 'items'
我不太确定出了什么问题。任何帮助将不胜感激。
(以防万一它有用,这是我的views.py :)
@views.route("/test", methods=["GET"])
@login_required
def test():
countries = Country.query.all()
for country in countries:
countriess = {}
countriess[country.country_code] = country.country_name
print(countriess)
return render_template("TEST.html", user=current_user, countries=countriess)
【问题讨论】:
标签: python dictionary flask iteration jinja2