jinja2递归循环vs字典

Tar*_*ula 8 python jinja2

我有以下字典:

{'a': {'b': {'c': {}}}}
Run Code Online (Sandbox Code Playgroud)

以下是Jinja2模板:

            {% for key in dictionary recursive %}

            <li>{{ key }}
            {% if dictionary[key] %}
                <ul>{{ loop(dictionary[key]) }}</ul>
            {% endif %}
            </li>

        {% endfor %}
Run Code Online (Sandbox Code Playgroud)

但Jinja2总是输出:

<ul>
    <li>a</li>
    <ul>
        <li>b</li>
    </ul>
</ul>
Run Code Online (Sandbox Code Playgroud)

我的理解是使用递归,它也会向我显示"c"元素,但它只适用于2的深度.为什么dictionary不改变到dictionary[key]每个循环迭代?的dictionary始终是原来的dictionary.

jco*_*ado 9

你是对的,dictionary没有在递归调用中更新,并且循环无法继续,因为找不到键.

解决此问题的方法是仅使用for循环中指定的变量.在字典示例中,这意味着迭代字典的项而不仅仅是键:

from jinja2 import Template

template = Template("""                                                     
{%- for key, value in dictionary.items() recursive %}                       
  <li>{{ key }}                                                             
    {%- if value %}                                                         
      Recursive {{ key }}, {{value}}                                        
      <ul>{{ loop(value.items())}}</ul>                                     
    {%- endif %}                                                            
  </li>                                                                     
{%- endfor %}                                                               
""")

print template.render(dictionary={'a': {'b': {'c': {}}}})
Run Code Online (Sandbox Code Playgroud)

该脚本的输出是:

<li>a
    Recursive a, {'b': {'c': {}}}
    <ul>
<li>b
    Recursive b, {'c': {}}
    <ul>
<li>c
</li></ul>
</li></ul>
</li>
Run Code Online (Sandbox Code Playgroud)

在这里你可以看到的是递归的b罚款,因为这两个关键工程keyvalue更新在每次循环(我加了"递归键,值"消息模板要清楚).