Include and Template Hierarchy
n
The include tag is a powerful tool for template reusability, but it has specific rules regarding its interaction with template inheritance. It’s crucial to understand this behavior to avoid unexpected rendering issues and to build a robust template hierarchy.
nn
The Basic Rule
n
The fundamental rule of the include tag is that while the included template can extend another template and override its blocks, the current template (the one doing the including) cannot override any blocks that are part of the included template’s output. In simpler terms, the include tag inserts rendered content, not a template with active blocks that can be manipulated by the parent.
nn
nn
Code Demonstration
n
Let’s consider a scenario where you have a base.html template and an included_part.html that extends it. We’ll then try to include included_part.html in main.html.
nn
base.html (the base template)
n
<!DOCTYPE html>n<html>n <head><title>Inherited Title</title></head>n <body>{% block body %}{% endblock %}</body>n</html>
n
included_part.html (extends the base template)
n
{% extends "base.html" %}n{% block body %}n This is content from the included template.n{% endblock %}
n
main.html (includes the other templates)
n
<!-- This will output the fully rendered content from included_part.html -->n{% include 'included_part.html' %}
n
In this example, the main.html file will output the full HTML from included_part.html, including its extension of base.html. The main.html template has no control over the blocks defined within included_part.html and cannot override them. This behavior is by design and is a key difference between include and extends.
nn
n
n
