Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 and Json

I have for example a JSON File

{
    "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"
    }
}

As you can see I have under the section Google a Nested Section named Apps

With CherryPy I hand over this JSON Object as following with the name 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)

What I want is to render following:

  1. Google
    • Web (as a link)
    • Google Main
    • G+
    • Apps
      • Drive
      • Dropbox
  2. Social
    • Facebook
    • G+
    • Xing

and so on

What I don't understand is to do is to render this nested Objects like "Apps" recursively

like image 236
lennykey Avatar asked Aug 12 '12 14:08

lennykey


1 Answers

The documentation reads:

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.

In your case this would be accomplished with the following:

<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>
like image 195
Ryon Sherman Avatar answered Oct 02 '22 20:10

Ryon Sherman