例如我有一个 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"
}
}
如您所见,我在 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)
我想要的是呈现以下内容:
- 谷歌
- 网络(作为链接)
- 谷歌主页
- Google+
- 应用程序
- 开车
- 投递箱
- 社交
- Google+
- 兴
等等
我不明白的是递归地渲染这个嵌套的对象,比如“Apps”
最佳答案
It is possible to use loops recursively. This is useful if you are dealing with recursive data such as sitemaps. To use loops recursively you basically have to add the recursive modifier to the loop definition and call the loop variable with the new iterable where you want to recurse.
在您的情况下,这将通过以下方式完成:
<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>
关于python - Jinja2 和 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11922893/