简体   繁体   中英

How to display a nested dictionary using jinja2?

I have the following dictionary:

result = {1: {4: {6: {}, 7: {}, 8: {}}, 5: {}}, 2: {}, 3: {}}

My goal is to display it showing its hierarchy like so:

1
    4
       6
       7
       8
    5
2
3

I was able to achieve my goal using a recursive function in python:

def pretty(d, indent=0):
    msg = ''
    for key, value in d.items():
        msg += '\t' * indent + str(key) + '\n'
        if isinstance(value, dict):
            msg += pretty(value, indent+1)
        else:
            msg += '\t' * (indent+1) + str(value) + '\n'
    return msg

msg = pretty(result)
print(msg)

Now I would like to pass the dictionary to the render_template function of the flask library and use jinja2 in order to replicate the same result. I tried the following line of code but nothing happens:

{%- for key, value in result.items() recursive%}
    {{loop(value.items())}}
{%- else  %}
    {{value}}
{%- endif %}
{%- endfor%}

Would you be able to suggest a smart and elegant way to achieve my goal?

Note: I based my answer on this question .

Your template must print the keys rather than the values.

A convenient way to know the recursion depth (for the indentation) is the loop.depth0 variable.

So try this:

from jinja2 import Template

result = {1: {4: {6: {}, 7: {}, 8: {}}, 5: {}}, 2: {}, 3: {}}

template = Template(
"""
    {% for key, value in dict.items() recursive %}
        {{'\t' * loop.depth0}}{{key}}
        {{-loop(value.items())-}}
    {% endfor %}
""")

print (template.render(dict=result))

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