Additional Inheritance in Django
Additional Inheritance in Django
INSTITUTE OF TECHNOLOGY,
BENGALURU - 560109
LABORATORY MANUAL 2023-2024 EVEN SEMESTER
Inheritance
In Django, template inheritance allows you to build complex web pages by reusing a common
layout across multiple templates. This approach promotes DRY (Don't Repeat Yourself)
principles by enabling you to define a base template that other templates can extend.
First, create a base template that includes the common structure and elements for your site, such
as the header, footer, and navigation bar. This template will define blocks that child templates
can override.
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>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about/">About</a></li>
</ul>
</nav>
<main>
{% block content %}{% endblock %}
</main>
<footer>
<p>© 2024 My Site</p>
</footer>
</body>
</html>
Next, create child templates that extend the base template. These templates will fill in the content
for the blocks defined in the base template.
home.html:
{% extends "base.html" %}
{% block content %}
<h2>Home Page</h2>
<p>Welcome to the homepage of My Site. Here you'll find the latest updates
and news.</p>
{% endblock %}
about.html:
{% extends "base.html" %}
{% block content %}
<h2>About Us</h2>
<p>Learn more about My Site and what we do. We are passionate about providing
great content and services to our users.</p>
{% endblock %}
In these child templates:
{% block title %} and {% block content %} override the corresponding blocks in the base
template.
Make sure your URL patterns and views are set up to render these templates.
urls.py:
def home(request):
return render(request, 'home.html')
def about(request):
return render(request, 'about.html')
4. Run Your Server
Start your Django development server to see the template inheritance in action:
http://127.0.0.1:8000/about/
Summary
Template inheritance in Django allows you to define a base template and extend it in child
templates. This helps maintain a consistent look and feel across your site while making it easier
to manage and update. By using blocks, you can customize specific sections of your pages
without duplicating the overall layout.