【问题标题】:Django | Template | Correct way to iterate over list of dictionaries姜戈 |模板 |迭代字典列表的正确方法
【发布时间】:2014-05-18 03:11:32
【问题描述】:

我有一个名为 messages 的变量,其中包含我传递给模板的字典列表, 这应该遍历列表并打印值 每个字典中的键“html”。

词典列表

[
 '{"body": "asdada", "html": "sfdsfsfw", "id": "sdfsfsf"}',
 '{"body": "dgdgdg", "html": "sfdsfsfs", "id": "sfsfsdf"}', 
 '{"body": "dgeaeg", "html": "sfdaewaa", "id": "sfwaeaw"}'
]

模板示例

{% for message in messages %}
{{ message.html }}
{% endfor %}

当我的网页被渲染时,这个for循环什么都不打印。我的意思是它在我的浏览器中得到的网页中的空白。我期待它打印

sfdsfsfw
sfdsfsfs
sfdaewaa

我在下面尝试过,但这给出了 TemplateSyntaxError

{% for message in messages %}
{{ message["html"] }}
{% endfor %}

需要帮助找出正确的方法来打印出键 "html" 的值。 请帮忙!

【问题讨论】:

  • 不是字典列表,而是字符串列表。 ('...')
  • 嗨,你是对的。愚蠢的我。请将此写为答案,以便我接受并关闭此问题。

标签: python django django-templates


【解决方案1】:

以下不是字典列表,而是字符串列表。

[
 '{"body": "asdada", "html": "sfdsfsfw", "id": "sdfsfsf"}',
 '{"body": "dgdgdg", "html": "sfdsfsfs", "id": "sfsfsdf"}', 
 '{"body": "dgeaeg", "html": "sfdaewaa", "id": "sfwaeaw"}'
]

字符串对象没有html属性/项;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-18
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 2016-05-16
    • 2019-07-12
    相关资源
    最近更新 更多