选择性覆盖Jinja2

时间:2015-08-12 06:26:46

标签: python flask jinja2

public ObservableCollection<SelectableObject<Module>> Modules { get; private set; }

是否可以在{% block very_outer_block %} {%block outer_block%} <p> "howdy wassup up" </p> <p>{% block inner_block%} "I want to be overridden" {%endblock%}</p> {%endblock%} {%endblock%} 上致电super(),但可以覆盖outer_block

以便inner_block覆盖inner_block时输出为"Im another text",例如:

<p> "howdy wassup" </p>
<p> "Im another text" </p>

或者我们会将inner_block覆盖为"Overridden yet again" 所以它会是:

<p> "howdy wassup" </p>
<p> "Overridden yet again" </p>

我的问题是,如果我们在块中定义块,我们可以在super()上调用outer_block但是覆盖inner_block吗?

1 个答案:

答案 0 :(得分:3)

你可以像这样覆盖内部块;块是否嵌套在其他块中并不重要。只要你不覆盖那些(如果不重新定义它们会使内部块不存在),它就可以正常工作:

>>> base = '''
{% block very_outer_block %}
    {%block outer_block%}
        <p> "howdy wassup up" </p>
        <p>{% block inner_block%}  "I want to be overridden"  {%endblock%}</p>
    {%endblock%}
{%endblock%}
'''
>>> test = '''
{% extends 'base' %}
{% block inner_block %}Overriding inner only{% endblock %}
'''
>>> env = jinja2.Environment(loader=jinja2.DictLoader({ 'base': base, 'test': test }))
>>> print(env.get_template('test').render().strip('\n'))

        <p> "howdy wassup up" </p>
        <p>Overriding inner only</p>