【问题标题】:Loop over arbitrarily nested data in a Jinja template循环遍历 Jinja 模板中的任意嵌套数据
【发布时间】:2019-04-09 08:38:59
【问题描述】:

我有以下 dicts 列表,其中每个 dicts 可以有一个 children 键和进一步的 dicts 列表。这可以嵌套任意深度。如何在 Jinja 中循环输出嵌套列表?

[{
    'id': '1',
    'name': 'Level 1',
    'children': [{
        'id': '11',
        'name': 'Level 1.1'
    }, {
        'id': '12',
        'name': 'Level 1.2'
    }, {
        'id': '13',
        'name': 'Level 1.3',
        'children': [{
             'id': '131',
             'name': 'Level 1.3.1'
         }]
    }]
},
{
    'id': '2',
    'name': 'Level 2',
    'children': [{
        'id': '21',
        'name': 'Level 2.1'
    }]
}]

【问题讨论】:

    标签: python jinja2


    【解决方案1】:

    for 循环中使用recursive 选项。现在调用特殊的loop 变量将使用嵌套内容重复循环。

    <ul>
        {% for item in data recursive %}
        <li>{{ item.name }}
        {% if item.children %}
            <ul>{{ loop(item.children) }}</ul>
        {% endif %}</li>
        {% endfor %}
    </ul>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-01
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多