python - Jinja2 和 Json

标签 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"
    }
}

如您所见,我在 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)

我想要的是呈现以下内容:

  1. 谷歌
    • 网络(作为链接)
    • 谷歌主页
    • Google+
    • 应用程序
      • 开车
      • 投递箱
  2. 社交
    • Facebook
    • Google+

等等

我不明白的是递归地渲染这个嵌套的对象,比如“Apps”

最佳答案

documentation阅读:

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/

相关文章:

python - 属性错误 : 'module' object has no attribute python

Python:类静态成员指向自身?

python - 找到 2 个堆栈的交集的最快和最有效的方法

pyramid - Jinja2 扩展不工作?

python - 在 Django 中更新条件

mysql - JSON JSON_EXTRACT 与 MySQL

javascript - 从数据对象设置多个标记 Google map

ruby-on-rails - 如何在 Rails 3.2 中使用 JBuilder 渲染 json

Jinja2 从与工作目录不同的位置加载模板

python - 如何使用 Jinja2 模板解码 flask 中的 &#39