【问题标题】:Django template in nested dictionary嵌套字典中的 Django 模板
【发布时间】:2014-03-04 14:02:54
【问题描述】:

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

字典:

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

我的 HTML 文件中的模板是:

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

如何只显示 type_0 和 type_1 的值?

我试过了:

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

但它不起作用。

感谢您的帮助。

【问题讨论】:

    标签: python django dictionary django-templates


    【解决方案1】:

    使用dict.itemsdict.values

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

    交互式 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'}
    

    【讨论】:

    • 他如何访问嵌套字典中的值?例如。 {{ value.file_name }}?
    • @RobertGrant,是的。为什么不在 django shell 中进行测试?上面的例子是从 django shell 复制过来的。
    • 对不起,我实际上是在 sopython 聊天室里找其他人 :) 在没有 Python 的笔记本电脑上。悲伤的时光。
    猜你喜欢
    • 2021-01-16
    • 1970-01-01
    • 2021-12-20
    • 2011-10-11
    • 2020-08-03
    • 1970-01-01
    • 2013-11-18
    • 2013-09-19
    • 2020-06-18
    相关资源
    最近更新 更多