Template Inheritance in Django: How It Works and When to Use
{% extends %} tag. It helps reuse common page parts like headers and footers, letting you change the base layout once to update all pages.How It Works
Template inheritance in Django works like a family tree for your web pages. Imagine you have a master blueprint for a house that includes the main structure, roof, and walls. Each room in the house can then have its own design but still follow the main blueprint. In Django, the base template is the blueprint, and other templates extend it to add or change parts.
This is done using the {% extends 'base.html' %} tag at the top of a child template. The base template defines {% block %} sections as placeholders. Child templates fill these blocks with their own content. This way, you keep your layout consistent and avoid repeating the same HTML in every file.
Example
This example shows a base template with a header and footer, and a child template that fills the main content area.
<!-- base.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}My Site{% endblock %}</title> </head> <body> <header> <h1>Welcome to My Site</h1> </header> <main> {% block content %}{% endblock %} </main> <footer> <p>© 2024 My Site</p> </footer> </body> </html> <!-- home.html --> {% extends "base.html" %} {% block title %}Home Page{% endblock %} {% block content %} <p>This is the home page content.</p> {% endblock %}
When to Use
Use template inheritance when you have multiple pages sharing the same layout parts like headers, footers, or navigation menus. It saves time and effort by letting you update the layout in one place instead of editing every page.
For example, a blog site with many posts can use a base template for the common design and extend it for each post's unique content. It also helps keep your code clean and easier to maintain as your site grows.
Key Points
- Template inheritance uses
{% extends %}to build on a base template. - Base templates define
{% block %}tags as placeholders for child templates. - It promotes code reuse and consistent layouts across pages.
- Changing the base template updates all pages that extend it.