嵌套字典中的Django模板 [英] Django template in nested dictionary

查看:108
本文介绍了嵌套字典中的Django模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django模板,并且遇到了嵌套字典的一个问题。

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

字典:

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

,我的HTML文件中的模板为:

and the template in my HTML file is:

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

如何仅显示type_0和type_1的值?

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

我尝试过:

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

谢谢您的帮助。

推荐答案

使用 dict.items 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'}

这篇关于嵌套字典中的Django模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆