在Django模板中遍历字典索引
我有一个字典,里面嵌套了一些对象,结构大概是这样的:
notes = {
2009: [<Note: Test note>, <Note: Another test note>],
2010: [<Note: Third test note>, <Note: Fourth test note>],
}
我想在django模板中访问每一个笔记对象,但在找到它们的过程中遇到了很多麻烦。简单来说,我不太确定如何在django模板中通过索引来提取这些对象。
我现在的模板代码是:
<h3>Notes</h3>
{% for year in notes %}
{{ year }} # Works fine
{% for note in notes.year %}
{{ note }} # Returns blank
{% endfor %}
{% endfor %}
如果我把{% for note in notes.year %}替换成{% for note in notes.2010 %},那就能正常工作,但我需要这个'2010'是动态的。
非常感谢任何建议。
1 个回答
8
试试:
<h3>Notes</h3>
{% for year, notes in notes.items %}
{{ year }}
{% for note in notes %}
{{ note }}
{% endfor %}
{% endfor %}