Displaying nested dictionary in Jinja2

一世执手 提交于 2021-02-18 08:16:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!