Question

A newbie django template question, hope to get some pointers.

I'm passing back a dictionary to render to html for a page. The structure of the dictionary is like the following:

dic:{
    "names":["name1", "name2", "name3"],
    "names1":{
          "addresses":["address1","address2","address3"],   
          "key2":[......]
          ......
          }
    "name2":{......}
    }

How do I access the inner dictionaries? The only way to know the keys for those inner dictionaries is from the list, but I was unable to iterate through values pointed by key "names" and use that value as a key to get the other dictionary. I have looked into writing customer filters/tags but not sure exactly how to proceed.

Was it helpful?

Solution

Use items, from django docs:

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}

I tested it with your example:

In template:

<ul>
  {% for l1_key, l1_value in dic.items %}
  <li>{{ l1_key }}:
    <ul>
      {% for l2_key, l2_value in l1_value.items %}
      <li>{{ l2_key }}: {{ l2_value }}</li>
      {% empty %}
      <li>{{ l1_value }}</li>
      {% endfor %}
    </ul>
  </li>
  {% endfor %}
</ul>

This will output something like:

- name2:
    - address: [1, 2, 3]
- names:
    - ['name1', 'name2', 'name3']
- names1:
    - key2: [1, 2]
    - addresses: ['address1', 'address2', 'address3']

items return a list of tuples formed by (key, value)

I used this dic (fix minor problems in your example):

dic = {
    "names":["name1", "name2", "name3"],
    "names1":{
        "addresses":["address1","address2","address3"],
        "key2":[1,2]
    },
    "name2":{'address':[1,2,3]}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top