我有一本字典,其中包含所有國家/地區代碼和相應的國家/地區名稱,其中的示例如下所示:
{'AF': 'Afghanistan'}
{'AL': 'Albania'}
{'DZ': 'Algeria'}
{'AD': 'Andorra'}
{'AO': 'Angola'}
當我關注這個堆疊溢位問題時:如何遍歷 Jinja 模板中的字典串列?嘗試遍歷我遇到問題的國家,因為它沒有添加任何元素。這是我的代碼:
{% 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)
uj5u.com熱心網友回復:
嘗試更改views.py為:
@views.route("/test", methods=["GET"])
@login_required
def test():
countries = Country.query.all()
countriess = []
for country in countries:
countriess.append({country.country_code: country.country_name})
return render_template("TEST.html", user=current_user, countries=countriess)
此代碼將創建一個字典串列,countries無需更改模板代碼。
uj5u.com熱心網友回復:
在 中views.py,您設定countries=countriess為模板渲染。在函式(countriess = {})countriess的for回圈中重新初始化test,因此countriess傳遞給模板的實際上是串列中{country_code: country_name}最后一個國家的一對countries。
回到實際的錯誤:當你countries在模板 ( {% for dict_item in countries %}) 中迭代字典時,你實際上迭代了 的鍵countries,正如我之前所說,它countriess來自views.py,所以基本上你只是從 中檢索country_code最后一個國家的countries。所以 dict_item 實際上是一個字串(國家/地區代碼),因此您會收到錯誤{% for key,value in dict_item.items %},認為它實際上是一個字典而不是一個字串。
TL;DR 我認為你的意思是做countries=countries而不是countries=countriess在views.py. 那么其余的代碼就有意義了。(我假設 for 回圈countriess只是為了除錯?)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/329497.html
