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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With