Zion
Zion

Reputation: 1610

Selective Override Jinja2

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

Is it possible to call super() on the outer_block but override the inner_block?

so that the output would be if inner_block was overidden to "Im another text" for example:

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

or if we'll override inner_block to "Overridden yet again"
so it'll be:

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

my question is if we define blocks within blocks can we call super() on the outer_block yet override the inner_block?

Upvotes: 2

Views: 283

Answers (1)

poke
poke

Reputation: 387587

You can just override the inner block like this; it doesn’t matter if the block is nested inside others. As long as you don’t overwrite those (which would make the inner blocks non-existent if you don’t redefine them), it will work just fine:

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

Upvotes: 3

Related Questions