Template inheritance helps you reuse common parts of your web pages easily. It saves time and keeps your code neat.
0
0
Template inheritance with base template in Django
Introduction
You want all pages on your website to share the same header and footer.
You need to change the look of many pages by editing just one file.
You want to keep your HTML organized by separating common layout from page content.
You are building a website with many pages that have a similar structure.
You want to avoid repeating the same HTML code in multiple templates.
Syntax
Django
{% extends "base.html" %}
{% block content %}
<!-- Your page content here -->
{% endblock %}Use
{% extends %} at the very top of your child template to inherit from the base template.Define
{% block %} sections in your base template that child templates can fill or override.Examples
This child template sets the page title and content inside the blocks defined in the base template.
Django
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
{% block content %}
<p>Welcome to the home page!</p>
{% endblock %}This child template only overrides the content block, leaving other parts from the base template unchanged.
Django
{% extends "base.html" %}
{% block content %}
<h1>About Us</h1>
<p>Information about our company.</p>
{% endblock %}Sample Program
The base.html file defines the common page layout with blocks for title and content. The home.html file inherits from base.html and fills in the title and content blocks with page-specific information.
Django
{# base.html #}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
<header>
<h1>My Website Header</h1>
</header>
<main>
{% block content %}
<p>Default content.</p>
{% endblock %}
</main>
<footer>
<p>© 2024 My Website</p>
</footer>
</body>
</html>
{# home.html #}
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
{% block content %}
<p>Welcome to the home page!</p>
{% endblock %}OutputSuccess
Important Notes
Always put {% extends %} at the very top of your child template file.
Blocks in the base template act like placeholders that child templates can fill.
If a child template does not override a block, the base template's content for that block is used.
Summary
Template inheritance lets you reuse common page parts easily.
Use {% extends %} to inherit and {% block %} to define replaceable sections.
This keeps your templates clean and easy to maintain.