簡體   English   中英

在flask jinja中迭代python字典

[英]Iterating through a python dictionary in flask jinja

我有一本字典,其中包含所有國家/地區代碼和相應的國家/地區名稱,其中的示例如下所示:

{'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)

嘗試將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列表,無需更改模板代碼。

views.py ,您為模板渲染設置了countries=countriess countriess是重新初始化在for在環test功能(countriess = {}),所以countriess傳遞下去的模板其實是一個{country_code: country_name}對來自最后一個國家countries名單。

回到實際的錯誤:當你在模板中迭代countries字典( {% for dict_item in countries %} )時,你實際上迭代了countries鍵,正如我之前所說,這是來自views.py countriess ,所以基本上你只需從countries檢索最后一個國家的country_code 所以 dict_item 實際上是一個字符串(國家代碼),因此你會得到{% for key,value in dict_item.items %} ,認為它實際上是一個字典而不是一個字符串。

TL;DR 我認為你的意思是在views.pycountries=countries而不是countries=countriess 那么其余的代碼就有意義了。 (我假設與循環countriess只是進行調試?)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM