如何使用jinja变量在Django模板的字典中迭代字典?
我的字典如下:
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
},
}
我想遍历字典并显示名称"和国家"的所有值.
I want to loop through the dict and display all values for "name" and "country".
.html模板中的代码如下:
my code in my .html template looks like:
{% for c in a %}
<thead>{{ a[c]['country'] }}</thead>
{% endfor %}
{% for n in a %}
<tr>
<td>{{ a[n]['name'] }}</td>
</tr>
{% endfor %}
这给出了一个错误:
无法解析其余部分:"[c] ['country']' '同事[c] ['国家']'
Could not parse the remainder: '[c]['country']' from 'leagues[c]['country']'
我也尝试过
{% for c in leagues %}
<thead>{{ leagues.c.country }}</thead>
{% endfor %}
{% for n in leagues %}
<tr>
<td>{{ a.n.name }}</td>
</tr>
{% endfor %}
页面空白.
如何定位值的名称和国家/地区?
How do I target the values name and country?
您不使用Jinja ,您使用的是Django模板语言.
You are not using Jinja, you are using Django template language.
但是,这不是您在Python中遍历字典或列表的方式.当您执行for x in whatever
时,x
是实际元素,而不是索引.另外,当您要遍历字典的值时,需要使用values
方法.
But this is not how you loop through dicts or lists in Python. When you do for x in whatever
, x
is the actual element, not the index. Also, when you want to loop through the values of a dict, you need to use the values
method.
{% for league in leagues.values %}
<thead>{{ league.country }}</thead>
{% endfor %}
{% for league in leagues.values %}
<tr>
<td>{{ league.name }}</td>
</tr>
{% endfor %}