簡體   English   中英

我在我的代碼中使用Jinja2“遞歸”標記,但是如何獲得當前循環的深度?

[英]I use Jinja2 “recursive” tag in my code,but how can I get the depth of current loop?

我使用標簽“recursive”作為文檔:

<ul class="sitemap">
{%- for item in sitemap recursive %}
    <li><a href="{{ item.href|e }}">{{ item.title }}</a>
    {%- if item.children -%}
        <ul class="submenu">{{ loop(item.children) }}</ul>
    {%- endif %}</li>
{%- endfor %}
</ul>

但我想知道當前循環的深度和父循環索引。 我怎么才能得到它?

嘗試一組loop.index值,其中在每次調用loop()之前保存父索引,然后立即彈出。 要在不渲染文本的情況下修改數組,請啟用{% do ... %}語句。

例:

template = """
{%- set idxs = [0] -%}
{%- for item in sitemap recursive %}
    depth={{idxs|length}}. idx={{loop.index}}. pidx={{idxs[-1]}}. title={{item.title}}
    {%- if item.children -%}
        {%- do idxs.append(loop.index) -%}
        {{ loop(item.children) }}
        {%- do idxs.pop() -%}
    {%- endif %}
{%- endfor %}
"""

class Node():
    def __init__(self, title, children=[]):
        self.title = title
        self.children = children

sitemap = [
    Node('a', [
        Node('a_a', [
            Node('a_a_a'),
            ]),
        Node('a_b', [
            Node('a_b_a', [
                Node('a_b_a_0'),
                ]),
            ]),
        ]),
    Node('b'),
    ]

env = jinja2.Environment(extensions=['jinja2.ext.do'])
print env.from_string(template).render(sitemap=sitemap)

該程序打印:

    depth=1. idx=1. pidx=0. title=a
    depth=2. idx=1. pidx=1. title=a_a
    depth=3. idx=1. pidx=1. title=a_a_a
    depth=2. idx=2. pidx=1. title=a_b
    depth=3. idx=1. pidx=2. title=a_b_a
    depth=4. idx=1. pidx=1. title=a_b_a_0
    depth=1. idx=2. pidx=0. title=b

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM