Django template in nested dictionary

那年仲夏 提交于 2019-12-11 02:47:22

问题


I am using Django template, and I met one problem with nested dictionary.

Dict:

result_dict = {'type_0' : {'file_name' : 'abc', 'count' : 0},
               'type_1' : {'file_name' : 'xyz', 'count' : 50}}

and the template in my HTML file is:

{% for type in result_dict %}
    {{ type }}, {{ type.file_name }}
{% endfor %}

How can I show the value of type_0 and type_1 only ?

I've tried:

{% for key, value in result_dict %}
    {{ key }}, {{ value }}
{% endfor %}

but it doesn't work.

Thank you for your help.


回答1:


Use dict.items or dict.values:

{% for key, value in result_dict.items %}
    {{ value }}
{% endfor %}

Example in interactive shell:

>>> result_dict = {'type_0' : {'file_name' : 'abc', 'count' : 0},
...                'type_1' : {'file_name' : 'xyz', 'count' : 50}}
>>>
>>> t = Template('''
... {% for key, value in result_dict.items %}
...     {{ value }}
... {% endfor %}
... ''')
>>> print(t.render(Context({'result_dict': result_dict})))


    {'count': 50, 'file_name': 'xyz'}

    {'count': 0, 'file_name': 'abc'}

>>> t = Template('''
... {% for key, value in result_dict.items %}
...     {{ value|safe }}
... {% endfor %}
... ''')
>>> print(t.render(Context({'result_dict': result_dict})))


    {'count': 50, 'file_name': 'xyz'}

    {'count': 0, 'file_name': 'abc'}


来源:https://stackoverflow.com/questions/21623013/django-template-in-nested-dictionary

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