2012-08-12 15 views
7

ho per esempio, un JSON FileJinja2 e 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" 
    } 
} 

Come potete vedere ho sotto la sezione di Google una sezione annidata denominata Apps

Con CherryPy ho la mano su questo JSON oggetto di successivo con il nome 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) 

Quello che voglio è quello di rendere seguente:

  1. Google
    • Web (come un link)
    • Google principali
    • G +
    • Apps
      • Unità
      • Dropbox
  2. sociale
    • Facebook
    • G +
    • Xing

e così via

Quello che non capisco è da fare è di rendere questo nidificate oggetti come "Apps" ricorsivamente

risposta

13

Le letture 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.

Nel tuo caso questo sarebbe stato realizzato con il seguente:

<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> 
+0

Ehi Ryon, vi ringrazio molto. Era esattamente quello che stavo cercando. Ciò che è stato di aiuto è stato testare una stringa. Ho provato per un dict a got TemplateAssertionError: nessun test chiamato 'dict'. Perché non puoi testare un ditt o un elenco – lennykey

+2

@lennykey Sembra che Jinja non fornisca un [test integrato] (http://jinja.pocoo.org/docs/templates/#builtin-tests) per dict o list anche se è possibile [creare il proprio] (http://jinja.pocoo.org/docs/api/#writing-tests). –