在Jinja2中显示嵌套字典 [英] Displaying nested dictionary in Jinja2

查看:124
本文介绍了在Jinja2中显示嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Jinja2模板:

{% 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 %}

其中tree是Python字典,例如:

    tree = {"A": {"R": [1, 2, 3], "B": {"R": [4, 5, 6]}}}

dict() Python库函数.

问题在于模板仅显示[1, 2, 3]而不显示[1, 2, 3][4, 5, 6].

很明显,我对Jinja中递归的工作方式有误解.有什么提示吗?

解决方案

您为什么使用'double for'来控制它? 我正在尝试使用"single for"进行编码,如下所示:

 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 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?

解决方案

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 :)

这篇关于在Jinja2中显示嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆