1

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?

watermelon123
  • 357
  • 2
  • 3
  • 12

4 Answers4

2

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 ;-)

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
1

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.

Zack Turner
  • 216
  • 3
  • 14
  • not quite - I have passed the dictionary to my template, but I want to access keys 6, 7 and 8 which are nested inside the main context dictionary, and print their values – watermelon123 Apr 20 '20 at 13:29
  • made some eddits can you tell me if that works tried it on mine and it did – Zack Turner Apr 20 '20 at 13:44
0

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.

Mayur Fartade
  • 317
  • 3
  • 18
0

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 %}
watermelon123
  • 357
  • 2
  • 3
  • 12