代码之家  ›  专栏  ›  技术社区  ›  Andrew Cassidy

Jinja2子模板中循环作用域的访问父级

  •  3
  • Andrew Cassidy  · 技术社区  · 6 年前

    父.txt

    {% for dict in list_of_dictionaries %}
        {% block pick_dictionary_element %}
        {% endblock %}
    {% endfor %}
    

    子文件

    {% extends "parent.txt" %}
    {% block pick_dictionary_element %}
        {{ dict.a }}
    {% endblock %}
    

    儿童2.txt

    {% extends "parent.txt" %}
    {% block pick_dictionary_element %}
        {{ dict.b }}
    {% endblock %}
    

    然后:

    from jinja2 import Template, Environment, FileSystemLoader
    e = Environment(loader=FileSystemLoader("./"))
    e.get_template("child_one.txt").render(list_of_dictionaries=[{'a': 'a', 'b': 'b'}])
    

    产生空输出。如何访问 dict 父for循环的var?我有点想象金贾就在 pick_dictionary_element 孩子有其父对象的for循环作用域?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Stephen Rauch Afsar Ali    6 年前

    你要做的关键是 scoped 块上的关键字:

    {# parent.txt #}
    {% for dict in list_of_dictionaries %}
        {% block pick_dictionary_element scoped %}
        {% endblock %}
    {% endfor %}
    

    为什么这么难调试?

    你把名字用错了 dict 循环中:

    {% for dict in list_of_dictionaries %}
    

    这样做的副作用是子模板不容易抱怨,因为符号 迪克特 存在于其上下文中。如果相反,你做了如下事情:

    {# parent.txt #}
    {% for a_dict in list_of_dictionaries %}
        {% block pick_dictionary_element %}
        {% endblock %}
    {% endfor %}
    
    {# child_one.txt #}
    {% extends "parent.txt" %}
    {% block pick_dictionary_element %}
        {{ a_dict.a }}
    {% endblock %}
    

    你会被告知:

    jinja2.exceptions.UndefinedError:“a_dict”未定义

        2
  •  1
  •   shaun shia    6 年前

    从Jinja 2.2开始,可以通过将块设置为“scoped”来显式指定块中的变量可用,方法是将scoped修饰符添加到块声明中

    http://jinja.pocoo.org/docs/2.9/templates/#block-nesting-and-scope

    {# parent.txt #}
    {% for dict in list_of_dictionaries %}
        {% block pick_dictionary_element scoped %}
        {% endblock %}
    {% endfor %}