Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwriting a block within an `include`d template from an extended template

I have the following:

base.html

<html>
    {% include 'header.html' %}
    <div>
    {% block content %}Default Content{% endblock %}
    </div>
</html>

header.html

<header>
     {% block logo %}Logo 1{% endblock %}
</header>

homepage.html

{% extend 'base.html' %}
{% block logo %}Logo 2{% endblock %}
{% block content %}Yap Yap Yap{% endblock %}

Essentially, this doesn't work. When I render the homepage.html I get:

<html>
    <header>Logo 1</header>
    <div>Yap Yap Yap</div>
</html>

but If I move the code in header.html into base.html (i.e. get rid of the include altogether) it works ok. Can anyone explain why this is the case?

I have a feeling it has something to do with the included templates getting rendered after their parents have been rendered?

like image 402
Timmy O'Mahony Avatar asked Jan 27 '12 14:01

Timmy O'Mahony


People also ask

How do I override a Django template?

You can either put template overrides in your project's templates directory or in an application's templates directory. If you have app and project templates directories that both contain overrides, the default Django template loader will try to load the template from the project-level directory first.

Can you extend more than one template Django?

Use Django extends in multiple templates Note that you can extend the header. html to multiple HTML documents using the same document structure and DTL block content tags. This means the header can render in multiple templates. The example above extends the header template to a new HTML template called contact.

What is include in Django template?

The include tag allows you to include content from another template. Place the include tag exactly where you want the content to be displayed. This is useful when you have the same content for many pages.


1 Answers

from the docs

The include tag should be considered as an implementation of "render this subtemplate and include the HTML", not as "parse this subtemplate and include its contents as if it were part of the parent". This means that there is no shared state between included templates -- each include is a completely independent rendering process.

so the subtemplate (header.html) is getting fully rendered and inserted into the parent template (base.html), meaning there is no concept of the block for the child template (homepage.html) to overwrite

like image 166
Timmy O'Mahony Avatar answered Oct 19 '22 14:10

Timmy O'Mahony