{% for dict in list_of_dictionaries %}
{% block pick_dictionary_element %}
{% endblock %}
{% endfor %}
{% extends "parent.txt" %}
{% block pick_dictionary_element %}
{{ dict.a }}
{% endblock %}
{% 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'}])
产生一个空的输出。如何从父for循环访问dict
var?我有点想像jinja只是内联pick_dictionary_element
和孩子,而孩子具有其父对象的for循环作用域?
答案 0 :(得分:1)
从Jinja 2.2开始,您可以通过将范围限定符添加到块声明中,将块设置为“作用域”,从而明确指定变量在块中可用
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 %}
答案 1 :(得分:1)
要执行的操作的关键是在块上使用scoped
关键字:
{# parent.txt #}
{% for dict in list_of_dictionaries %}
{% block pick_dictionary_element scoped %}
{% endblock %}
{% endfor %}
您在循环中使用名称dict
犯了一个错误:
{% for dict in list_of_dictionaries %}
这样做的副作用是子模板不容易抱怨,因为符号dict
存在于上下文中。如果相反,您已经做过类似的事情:
{# 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'未定义