I've been learning Django through an Udemy course and got through Template Inheritance. From what I understand it works as follows:
templates/myapp/parent.html
<div class="container">
{% block child_block %}
{# delegated to child template #}
{% endblock %}
</div>
templates/myapp/child.html
<!DOCTYPE html>
{% extends "myapp/parent.html" %}
{% block child_block %}
<!-- child content -->
{% endblock %}
We have a parent template parent.html
and a child template child.html
. The parent template declares a block that it will delegate to the child template. The child template declares the parent it extends and then declares the same block with the content it contains. During page construction, Django will construct the parent template, reach the block, and fill it with the content declared by the child template ---with the stipulation that you don't use blocks with the same name in any given template (to prevent name collision).
This pattern works great for use-cases where a parent template may have multiple children and/or multiply nested children. You organize the template code more efficently and in smaller more manageable blocks. If a child were to be repeated N times (usually through a for loop), you delegate a block within the for loop to ensure each iteration uses the same template (DRY).
What about the reverse case?
What do we do for use-cases where more than one parent reuses a common child template? In Django-parlance, what about use-cases where a child template extends more than one parent template?
As an example, imagine we have an app with multiple pages that reuses some common view code (perhaps for a model they all use). The DRY principle tells me that it'd be best to abstract the common view code into a common template-- a child template in Django. This poses a problem though, because Django's child templates must declare their parent template in their extends
template tag.
Here's an example:
templates/myapp/parent_1.html
<div class="container">
{% block child_block %}
{# delegated to child template #}
{% endblock %}
</div>
templates/myapp/parent_2.html
<div class="container">
{% block child_block %}
{# delegated to child template #}
{% endblock %}
</div>
templates/myapp/child.html
<!DOCTYPE html>
{% extends "myapp/parent_?.html" %} {# extend which parent ??? #}
{% block child_block %}
<!-- child content -->
{% endblock %}
How then do we write child templates that extends more than one parent template?
Research
Perusing SO and some of the Django documentation, I see questions that are almost similar; but, they consistently refer to resuing a template block in the same page. The common answer appears to be using includes statement or using different block names and overriding the content in the child templates. This question, however, concerns the reuse of a template block across multiple pages (therefore having multiple parent templates).