Python Flask/Jinja2-在嵌套字典上迭代
我试图以一组嵌套的非有序列表的形式显示字典的内容和结构 我收集到的数据是这样的Python Flask/Jinja2-在嵌套字典上迭代,python,dictionary,flask,nested,jinja2,Python,Dictionary,Flask,Nested,Jinja2,我试图以一组嵌套的非有序列表的形式显示字典的内容和结构 我收集到的数据是这样的 {'.': {'walk.py': None, 'what.html': None, 'misc': {}, 'orders': {'order1.html': None, 'more': {'stuff.html': None}}}} 表示此目录树 .: misc/ orders/ walk.py what.html ./misc: ./orders: more/ order1.html ./or
{'.': {'walk.py': None, 'what.html': None, 'misc': {}, 'orders': {'order1.html': None, 'more': {'stuff.html': None}}}}
表示此目录树
.:
misc/ orders/ walk.py what.html
./misc:
./orders:
more/ order1.html
./orders/more:
stuff.html
我将如何使用Jinja2语法来迭代它?有没有更好的办法
谢谢你
编辑:我觉得自己很愚蠢。在再次寻找解决方案后,我发现了我想要的东西。我猜我的google fu第一次尝试时并没有真正支持我。
使用的
递归
修饰符(示例取自文档):
输出:
./
--walk.py
--what.html
--misc/
--orders/
----order1.html
----more/
------stuff.html
(Jinja2代码中的破折号(例如,
{%-…-%}
用于。请使用它。)首先组织数据:
a = {'.': {'walk.py': None, 'what.html': None, 'misc': {}, 'orders': {'order1.html': None, 'more': {'stuff.html': None}}}}
from collections import defaultdict
def f(data, path):
for k,v in data.iteritems():
if v is None:
yield path,k
else:
yield path,k+"/"
for k in f(v,path+k+"/"):
yield k
def process_data():
collect = defaultdict(list)
for p in f(a,""):
if p[0]:
collect[p[0][:-1]].append(p[1])
return collect
现在,如果您运行:
data = process_data()
for k in data.keys():
print k,data[k]
你会得到:
./orders ['order1.html', 'more/']
./orders/more ['stuff.html']
. ['walk.py', 'what.html', 'misc/', 'orders/']
这就是渲染所需的全部内容。模板应类似于:
{% for k in sitemap.keys()|sort -%}
{{ k }}:<br/>
{% for v in sitemap[k] %}
{{ v }}
{%- endfor %}
<br/>
{%- endfor %}
在我的测试中呈现为:
.:<br/>
walk.py
what.html
misc/
orders/
<br/>./orders:<br/>
order1.html
more/
<br/>./orders/more:<br/>
stuff.html
<br/>
:
步行
what.html
杂项/
命令/
/订单:
order1.html
更多/
/订单/更多:
stuff.html
为什么不只是一个嵌套的for循环
在your views.py中:
def index(request):
context={'main1':{'sub1','sub2','sub3'},'main2':{'sub1','sub2'}}
return render(request,'index.html',context)
在index.html中:
{% for key1,val in context.items %}
<p> {{ key1 }} </p>
<ul>
{% for key2 in val.items %}
<li> {{key2}} </li>
{% endfor %}
</ul>
{% endfor %}
{context.items%}
{{key1}}
{val.items%中的键2的%1}
- {{key2}}
{%endfor%}
{%endfor%}
如果成功了,你应该接受答案供其他人学习如果你知道树的确切深度,可以简单地使用嵌套for循环。但是你可能有更多的东西要写,而且在不知道传入数据的确切深度的情况下,有一个更通用的解决方案是非常好的。
.:<br/>
walk.py
what.html
misc/
orders/
<br/>./orders:<br/>
order1.html
more/
<br/>./orders/more:<br/>
stuff.html
<br/>
def index(request):
context={'main1':{'sub1','sub2','sub3'},'main2':{'sub1','sub2'}}
return render(request,'index.html',context)
{% for key1,val in context.items %}
<p> {{ key1 }} </p>
<ul>
{% for key2 in val.items %}
<li> {{key2}} </li>
{% endfor %}
</ul>
{% endfor %}