Reputation: 3076
I have following JSON document:
{
"document": {
"section1": {
"item1": "Item1Value",
"item2": "Item2Value"
},
"section2": {
"item1": "Item1Value",
"item2": "Item2Value"
},
"section3": {
"item1": "Item1Value",
"item2": "Item2Value"
}
}
}
Which I want to display in my django template. This document will be dynamic, so I want to display each sections dynamically. I am passing parsed (by json.loads()) string to the template.
I tried something like:
{% for section in json.document %}
<div class="section">
<h4><a href="#" class="section_toggle"></a> {{ section|title }}:</h4>
<table class="table table-condensed">
{% for field in json.document.section %}
{{ field }} {# <---- THIS should print item1, item2... Instead, its printing "section1" letter by letter etc #}
{% endfor %}
</table>
</div>
{% endfor %}
But it doesn't printting section's items properly. Any help?
Upvotes: 1
Views: 13880
Reputation: 47866
You can instead pass the dictionary to your template and access it by iterating over the values using dict.items
in your template.
{% for key1,value1 in json.document.items %}
<div class="section">
<h4><a href="#" class="section_toggle"></a> {{ key1|title }}:</h4>
<table class="table table-condensed">
{% for key2,value2 in value1.items %}
{{ key2 }}
{% endfor %}
</table>
</div>
{% endfor %}
In your code above, it was printing "section1"
letter by letter because you were not iterating over the values of the section1
key but on the section1
string itself. If you need to access the items in a dictionary, you need to use individual variables for keys and values and use dict.items
.
For example, the below code would print the keys and values of the data
dictionary in the template.
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}
Upvotes: 2