JSON on Django template

邮差的信 提交于 2019-12-11 17:13:31

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/49084214/json-on-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!