len*_*key 9 python json jinja2
我有一个JSON文件
{
"Google":{
"Web":"www.web.de",
"Apps":{
"Drive": "DriveLink",
"Dropbox": "DropboxLink"
},
"Google Main":"http://mail.google.com",
"G+":"http://plus.google.com"
},
"Social":{
"Facebook":"http://www.facebook.de",
"G+":"https://plus.google.com",
"Xing":"http://www.xing.de",
"LinkedIn":"http://www.linkedin.com",
"Tumblr":"http://www.tumblr.com"
},
"Fun":{
"Reddit":"http://www.reddit.com"
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我在Google部分下面有一个名为Apps的嵌套部分
使用CherryPy,我将此JSON对象移交给以下名称为linksList:
@cherrypy.expose
def index(self):
linksFile = open('links.json', 'r')
linksList = json.load(linksFile)
template = jinjaEnv.get_template('index.html')
return template.render(linksList=linksList)
Run Code Online (Sandbox Code Playgroud)
我想要的是呈现以下内容:
等等
我不明白的是要递归地渲染这个嵌套的对象,如"Apps"
Ryo*_*man 14
该文件内容如下:
可以递归地使用循环.如果您正在处理诸如站点地图之类的递归数据,这将非常有用.要递归地使用循环,您基本上必须将递归修饰符添加到循环定义中,并使用要迭代的新迭代函数调用循环变量.
在您的情况下,这将通过以下方式完成:
<ul>
{% for key, value in linksList.items() recursive %}
<li>
{% if value is string %}
<a href="{{ value }}">{{ key }}</a>
{% else %}
{{ key }}
<ul>{{ loop(value.items()) }}</ul>
{% endif %}
</li>
{% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18064 次 |
最近记录: |