2

I was wondering, when using templates in django, I'm able to extend other base templates and override some of the blocks in the base template. so my question is when I override, would the code in the overridden block still get rendered then overridden, or would it never be run and only the new block is rendered?

Example:

base.html

{% block menu %}
    {% for option in menu %}

       ...Create the menu entries

    {% endfor %}
{% endblock menu %}

extender.html

{% extends base.html %}

{% block menu %}
    ... some other tags
{% endblock menu %}

In this case does the original for loop in the base.html run if it gets overridden?

1 Answer 1

2

As far as I know the block will be overwritten unless you want to preserve its code in your extended template.

If you want to preserve the original block you can use {{ block.super }}

base.html

[...]
<body>
    {% block header %}
        base header content
    {% endblock %}
    [...]
</body>

extended.html

{% extends "base.html" %}
{% block header %}
    {{ block.super }}
    new content added
{% endblock %}
[...]

G.

Sign up to request clarification or add additional context in comments.

3 Comments

Nice! block.super is new to me, so to understand from your answer, if the base.html had a time consuming code in the block, it wont run because it is overridden?
Yes, that's what will happen! the engine ignores (get rid of) the code in your base template, so, if you do something like {% block header %}{% endblock %} it will render (and process) an empty string avoiding any loop or overload in the base template
Thanks @gariel, this is what im looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.