问题
I have the following Jinja2 template:
{% block body %}
{% for key in tree recursive %}
{% set outer_loop = loop %}
{% for subkey in tree[key] %}
{% if subkey == 'R' %}
{{ tree[key][subkey] }}
{% else %}
{{ outer_loop(dict([(subkey, tree[key][subkey])])) }}
{% endif %}
{% endfor %}
{% endfor %}
{% endblock body %}
where tree
is a Python dictionary such as:
tree = {"A": {"R": [1, 2, 3], "B": {"R": [4, 5, 6]}}}
and dict()
is the Python library function.
The issue is that the template displays only [1, 2, 3]
and not [1, 2, 3][4, 5, 6]
as expected.
Clearly I am misunderstanding something about how recursion works in Jinja; any hints?
回答1:
Why did you use the 'double for' to control it? I'm trying to use the 'single for' as follows to code and it looks like it is okay:
from jinja2 import Template
template = Template(
"""
{%- for key, value in tree.items() recursive%}
{%-if key != "R"%}
{{loop(value.items())}}
{%- else %}
{{value}}
{%- endif %}
{%- endfor%}
""")
print template.render(tree = {"A": {"R": [1, 2, 3], "B": {"R": [4, 5, 6]}}})
I hope it's useful to you with my poor english :)
来源:https://stackoverflow.com/questions/19931448/displaying-nested-dictionary-in-jinja2