watermelon123
watermelon123

Reputation: 417

Looping through nested dictionary in Django template

My context dictionary for my Django template is something like the following:

{'key1':'1',
'key2':'2',
'key3':'3',
'key4':{'key5':{'key6':'6', 'key7':'7', 'key8':'8'}}}

I would like to iterate through the dictionary and print something like:

some label = 6
some label = 7
some label = 8

How can I achieve this in my Django template?

Upvotes: 1

Views: 713

Answers (4)

Zack Turner
Zack Turner

Reputation: 226

I am guessing you want to use a for loop in the django template to do this you must first pass the dictionary to the template in the views file like so make sure you add square brackets around the dictionary like this:

 data = [{'key1':'1',
        'key2':'2',
        'key3':'3',
        'key4':{'key5':{'key6':'6', 'key7':'7', 'key8':'8'}}
        }]
return render(request,'name of template',{'data':data})

then in the html template:

{% for i in data%}
<p>{{i.key1}}</p>
<p>{{i.key2}}</p>
<p>{{i.key3}}</p>
<p>{{i.key4.key5.key6}}</p>
{% endfor %}

Now when you do the for loop you can access all the iteams in key4 like i have above when I put {{i.key4.key5.key6}} Here is the docs for the for loop in django templates https://docs.djangoproject.com/en/3.0/ref/templates/builtins/

I am assuming thats what you want to do.

Upvotes: 1

Mayur Fartade
Mayur Fartade

Reputation: 317

If you want to print only what you have mentioned in question then it is possible but if we don't know the exact structure of dictionary then it is possible in django views not in django template.

You can't print value which is also a dictionary one by one in django template, But you can do this in django view.

Check this post click here and do some changes in views.

Upvotes: 0

watermelon123
watermelon123

Reputation: 417

This has worked for me:

{% for key, value in context.items %}
{% ifequal key "key4" %}
{% for k, v in value.items %}
   some label = {{ v.key6 }}
   some label = {{ v.key7 }}
   some label = {{ v.key8 }}
{% endfor %}
{% endif %}
{% endfor %}

Upvotes: 0

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

What's wrong with this ?

<ul>
  {% for key, value in key4.key5.items %}
  <li>{{ key }} : {{ value }}</li>
   {% endfor %}
</ul>

NB: you didn't ask for looping over all keys in the context, just about accessing key4['key5'] content. if this wasn't wath you were asking for pleasit eadit your question to make it clearer ;-)

Upvotes: 2

Related Questions