在djang中将JSON显示为模板列表

2024-06-10 17:22:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下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 %}

但它并没有正确打印部分的项目。有什么帮助吗?


Tags: in文档div模板jsonfortablesection
1条回答
网友
1楼 · 发布于 2024-06-10 17:22:42

相反,您可以将字典传递给模板,并通过在模板中使用dict.items遍历值来访问它。

{% for key1,value1 in json.document.items %}
    <div class="section">
        <h4><a href="#" class="section_toggle"></a>  {{ key1|title }}:</h4>
        <table class="table table-condensed">
            {% for key2,value2 in value1.items %}
                {{ key2 }} 
            {% endfor %}
        </table>
    </div>

{% endfor %}

在上面的代码中,它逐字打印"section1",因为您不是在section1键的值上迭代,而是在section1字符串本身上迭代。如果需要访问字典中的项,则需要对键和值使用单个变量,并使用dict.items

例如,下面的代码将打印模板中data字典的键和值。

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}

相关问题 更多 >