【问题标题】:How to iterate through a dictionary in a dictionary in django template using django template tag?如何使用 django 模板标签遍历 django 模板中的字典中的字典?
【发布时间】:2019-10-22 02:56:04
【问题描述】:

我的字典是这样的:

a = {
            "1": {
                "league_id": "1",
                "name": "2018 Russia World Cup",
                "country": "World",
                "country_code": "",
                "season": "2018",
                "season_start": "2018-06-14",
                "season_end": "2018-07-15",
                "standings": False,
            },
            "2": {
                "league_id": "2",
                "name": "Premier League",
                "country": "England",
                "country_code": "GB",
                "season": "2018",
                "season_start": "2018-08-10",
                "season_end": "2019-05-12",
                "standings": True
            },
        }

我想遍历 dict 并显示“name”和“country”的所有值。

我的 .html 模板中的代码如下所示:

          {% for c in a %}
                 <thead>{{ a[c]['country'] }}</thead>
          {% endfor %}

          {% for n in a %} 
            <tr>
                <td>{{  a[n]['name'] }}</td>
            </tr>
          {% endfor %}

这给出了一个错误:

无法解析余数:'[c]['country']' from '联赛[c]['国家']'

我也试过

     {% for c in leagues %}
            <thead>{{ leagues.c.country }}</thead>
     {% endfor %}

     {% for n in leagues %}
            <tr>
                <td>{{  a.n.name }}</td>
            </tr>
    {% endfor %}

它给出了一个空白页。

如何定位值名称和国家/地区?

【问题讨论】:

    标签: json django python-3.x for-loop jinja2


    【解决方案1】:

    没有使用 Jinja,你使用的是 Django 模板语言。

    但这不是在 Python 中循环遍历字典或列表的方式。当您执行for x in whatever 时,x实际元素,而不是索引。另外,当你想遍历一个dict的值时,你需要使用values方法。

     {% for league in leagues.values %}
            <thead>{{ league.country }}</thead>
     {% endfor %}
    
     {% for league in leagues.values %}
            <tr>
                <td>{{ league.name }}</td>
            </tr>
    {% endfor %}
    

    【讨论】:

    • 循环有效。感谢对 jinja django 模板的澄清,我对 django 有点陌生。谢谢。
    • 如果它对您有帮助,请不要忘记接受答案,以向未来的搜索者表明它解决了您的问题。
    猜你喜欢
    • 2018-05-24
    • 2019-07-14
    • 2011-12-22
    • 2011-10-11
    • 1970-01-01
    • 2013-05-06
    • 2021-12-20
    • 2020-08-03
    • 2016-08-31
    相关资源
    最近更新 更多