Reputation: 145
While making a website, I ran into a problem. I am sending a JSON data from views.py to my template to print each attribute value from JSON data, but the data showing is empty.
data = {
"philip": {"age": 20, "salary": 10000},
"jerry": {"age": 27, "salary": 30000}
}
names = ["philip", "jerry"]
return render(request, 'index.html', {'data': data, 'names': names})
I'm storing the names from JSON data in a list and sending both data and names to template.
<div class="col-sm-3">
{% for name in names %}
{{ data.name }}
{% endfor %}
</div>
I want to get values associated with each name.
Upvotes: 0
Views: 2815
Reputation: 4213
You can just directly iterate over data
as below:
<div class="col-sm-3">
{% for person, data in data.items %}
{{ person }} - {{ data }} <br>
{% endfor %}
</div>
As iterate over key
and value
in dictionary.items()
in python the same way you can follow in template too.
So now you don't need to pass additional list of names to context.
Upvotes: 3