Skip to main content
 首页 » 编程设计

python之在 Django 模板中迭代字典索引

2025年05月04日29zlslch

我有一个包含嵌入式对象的字典,它看起来像这样:

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”是动态的。

非常感谢任何建议。

请您参考如下方法:

尝试:

<h3>Notes</h3> 
{% for year, notes in notes.items %} 
    {{ year }} 
    {% for note in notes %} 
        {{ note }} 
    {% endfor %} 
{% endfor %}