简体   繁体   English

如何在django模板中迭代带有列表的字典?

[英]How to iterate through a dictionary with lists in django template?

I have a dictionary with lists and I am trying to iterate through it, while in my Django template. 我有一个带有列表的字典,我正在尝试迭代它,而在我的Django模板中。

This is how it looks my dictionary: 这就是我的字典:

{u'Canada': [u'Saskatchewan', u'Nunavut', u'Nova Scotia / Nouvelle-\xc9cosse', u'Prince Edward Island / \xcele-du-Prince-\xc9douard', u'Northwest Territories / Territoires du Nord-Ouest', u'Ontario', u'Alberta', u'New Brunswick / Nouveau-Brunswick', u'Newfoundland and Labrador / Terre-Neuve-et-Labrador', u'British Columbia / Colombie-Britannique', u'Manitoba', u'Yukon', u'Quebec / Qu\xe9bec'], u'Sao Tome and Principe': [u'Principe', u'Sao Tome'],

The question is how to pass this dictionary to my template without having django escaping the characters and iterating all the values for each country. 问题是如何将这个字典传递给我的模板,而不必让django转义字符并迭代每个国家的所有值。

Right now I pass it in the context dictionary: 现在我在上下文字典中传递它:

ctx['regions'] = cntr_rgns

and then I try to iterate it in the template as: 然后我尝试在模板中迭代它:

{% if regions %}
    {% for cntr, rgn in regions.items %}
        <option value={{ region }}>{{ rgn }}</option>
     {% endfor %}
 {% endif %}

But this way I just get the whole array not each single element. 但是这样我只得到整个数组而不是每一个元素。

You should use a nested loop in your case: 你应该在你的情况下使用嵌套循环:

{% for cntr, rgn in regions.items %}
  {% for r in rgn %}
    <option value="{{ r }}">{{ r }}</option>
  {% endfor %}
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM