Flask/Jinja2 - 迭代嵌套词典

rem*_*bab 1 python dictionary nested jinja2 flask

我试图以一堆嵌套的无序列表的形式显示字典的内容和结构.

我设法拉到一起的数据看起来像这样,

{'.': {'walk.py': None, 'what.html': None, 'misc': {}, 'orders': {'order1.html':  None, 'more': {'stuff.html': None}}}}
Run Code Online (Sandbox Code Playgroud)

代表这个目录树,

.:
misc/  orders/  walk.py  what.html

./misc:

./orders:
more/  order1.html

./orders/more:
stuff.html
Run Code Online (Sandbox Code Playgroud)

我如何使用Jinja2语法对此进行迭代?这样做有更好的方法吗?

谢谢你的推荐.

编辑:我觉得很蠢.在再次寻找解决方案后,我发现了我正在寻找的东西.猜猜我的google-fu第一次尝试并不是真的和我在一起. 这里是...

dAn*_*jou 9

通过使用循环recursive修饰符(从文档中获取的示例):for

<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>
Run Code Online (Sandbox Code Playgroud)

UPDATE

这是我想出来的:

from jinja2 import Template

x = Template("""{%- for key, value in tree.iteritems() recursive %}
{{ '--' * (loop.depth-1) }}{{ key }}
{%- if value is mapping -%}/{{ loop(value.iteritems()) }}{%- endif -%}
{%- endfor %}
""")

tree = {'.': {
    'walk.py': None,
    'what.html': None,
    'misc': {},
    'orders': {
        'order1.html': None,
        'more': {
            'stuff.html': None
        }
    }
}}

print x.render(tree=tree)
Run Code Online (Sandbox Code Playgroud)

输出:

./
--walk.py
--what.html
--misc/
--orders/
----order1.html
----more/
------stuff.html
Run Code Online (Sandbox Code Playgroud)

(Jinja2代码中的破折号(例如{%- ... -%}用于空格控制.用它来玩.)