【问题标题】:django trouble iterating dict in template [duplicate]django在模板中迭代dict时遇到问题[重复]
【发布时间】:2014-12-19 05:43:31
【问题描述】:

我在模板中有以下数据

{u'D - content a': [<Person: first_name last_name>, <Person: first_name last_name>, <Person: first_name last_name>],
 u'D - contant b': [<Person: first_name last_name>],
 u'D - content c': [<Person: first_name last_name>]
 }

我想要这样:

h2 -> Content a
    list with three people

h2 -> content b
    list with one person

h3 -> content c
    list with one person

但我不知道两个是怎么写的。我的尝试:

    {% for key, value in persons %}
        <h2>{{ key }}</h2>
        {{ value }}
    {% endfor %}

【问题讨论】:

    标签: python django templates dictionary


    【解决方案1】:

    使用dict.items(或dict.iteritems,如果您使用Python 2.x):

    {% for item in persons.items %}
        <h2>{{ item.0 }}</h2>
        {{ item.1 }}
    {% endfor %}
    

    【讨论】:

    • 这正是我所需要的,谢谢。
    猜你喜欢
    • 2023-03-16
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2018-09-11
    • 2012-09-13
    • 1970-01-01
    相关资源
    最近更新 更多