在 django 中显示 JSON 作为模板列表

Display JSON as template list in django

我有以下 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 遍历值来访问它。

{% 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 %}