user1919
user1919

Reputation: 3938

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.

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.

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.

Upvotes: 4

Views: 2459

Answers (1)

Selcuk
Selcuk

Reputation: 59444

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 %}

Upvotes: 5

Related Questions