我有以下JSON文档:
{
"document": {
"section1": {
"item1": "Item1Value",
"item2": "Item2Value"
},
"section2": {
"item1": "Item1Value",
"item2": "Item2Value"
},
"section3": {
"item1": "Item1Value",
"item2": "Item2Value"
}
}
}
我想在我的django模板中显示。此文档将是动态的,因此我希望动态显示每个部分。我正在将解析的(json.loads())字符串传递给模板。
我试过这样的方法:
{% for section in json.document %}
<div class="section">
<h4><a href="#" class="section_toggle"></a> {{ section|title }}:</h4>
<table class="table table-condensed">
{% for field in json.document.section %}
{{ field }} {# <---- THIS should print item1, item2... Instead, its printing "section1" letter by letter etc #}
{% endfor %}
</table>
</div>
{% endfor %}
但它并没有正确打印部分的项目。有什么帮助吗?
相反,您可以将字典传递给模板,并通过在模板中使用
dict.items
遍历值来访问它。在上面的代码中,它逐字打印
"section1"
,因为您不是在section1
键的值上迭代,而是在section1
字符串本身上迭代。如果需要访问字典中的项,则需要对键和值使用单个变量,并使用dict.items
。例如,下面的代码将打印模板中
data
字典的键和值。相关问题 更多 >
编程相关推荐