简体   繁体   中英

Flask/Jinja2 - Iterating over nested dictionaries

I'm trying to display the contents and structure of a dictionary in the form of a bunch of nested un-ordered lists.

The data that I've managed to pull together looks like this,

{'.': {'walk.py': None, 'what.html': None, 'misc': {}, 'orders': {'order1.html':  None, 'more': {'stuff.html': None}}}}

which represents this directory tree,

.:
misc/  orders/  walk.py  what.html

./misc:

./orders:
more/  order1.html

./orders/more:
stuff.html

How would I go about iterating over this using the Jinja2 Syntax? Is there a better way go about doing this?

Thanks in advace.

EDIT: I feel stupid. After searching for a solution again I discovered exactly what I was looking for. Guess my google-fu wasn't really with me the first try. Here it is...

By using the recursive modifier of the for loop (example taken from the docs):

<ul class="sitemap">
{%- for item in sitemap recursive %}
    <li><a href="{{ item.href|e }}">{{ item.title }}</a>
    {%- if item.children -%}
        <ul class="submenu">{{ loop(item.children) }}</ul>
    {%- endif %}</li>
{%- endfor %}
</ul>

UPDATE

Here is something I came up with:

from jinja2 import Template

x = Template("""{%- for key, value in tree.iteritems() recursive %}
{{ '--' * (loop.depth-1) }}{{ key }}
{%- if value is mapping -%}/{{ loop(value.iteritems()) }}{%- endif -%}
{%- endfor %}
""")

tree = {'.': {
    'walk.py': None,
    'what.html': None,
    'misc': {},
    'orders': {
        'order1.html': None,
        'more': {
            'stuff.html': None
        }
    }
}}

print x.render(tree=tree)

Output:

./
--walk.py
--what.html
--misc/
--orders/
----order1.html
----more/
------stuff.html

(The dashes in the Jinja2 code (eg {%- ... -%} are for whitespace control . Play around with that.)

Why not just a nested for loop?

in your views.py:

def index(request):
    context={'main1':{'sub1','sub2','sub3'},'main2':{'sub1','sub2'}}
    return render(request,'index.html',context)

in your index.html:

{% for key1,val in context.items %}
    <p> {{ key1 }} </p>
    <ul>
    {% for key2 in val.items %}
            <li> {{key2}} </li>
    {% endfor %}
    </ul>
{% endfor %}

First organize the data:

a = {'.': {'walk.py': None, 'what.html': None, 'misc': {}, 'orders': {'order1.html':  None, 'more': {'stuff.html': None}}}}    

from collections import defaultdict

def f(data, path):
    for k,v in data.iteritems():
        if v is None:
            yield path,k
        else:
            yield path,k+"/"
            for k in f(v,path+k+"/"):
                yield k

def process_data():
    collect = defaultdict(list)
    for p in f(a,""):
        if p[0]:
            collect[p[0][:-1]].append(p[1])
    return collect

Now if you run:

data = process_data()
for k in data.keys():
    print k,data[k]

You get:

./orders ['order1.html', 'more/']
./orders/more ['stuff.html']
. ['walk.py', 'what.html', 'misc/', 'orders/']

Thats all you need for rendering. The template should be something like:

{% for k in sitemap.keys()|sort -%}
    {{ k }}:<br/>
    {% for v in sitemap[k] %}
    {{ v }}
    {%- endfor %}
    <br/>
{%- endfor %}

and the call for rendering:

@app.route("/")
def hello():
    return render_template('temp.html',sitemap=process_data())

Which in my test renders as:

.:<br/>    
walk.py
what.html
misc/
orders/
<br/>./orders:<br/>    
order1.html
more/
<br/>./orders/more:<br/>    
stuff.html
<br/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM