Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Template Inheritance in Django

Introduction

Template inheritance is a powerful feature in Django that allows you to create a base template and extend it to create different pages of your application. This helps in maintaining a consistent look and feel across your website or application by reusing common layout elements like headers, footers, and navigation bars.

Base Template

Let's start by creating a base template. This template will serve as the foundation for all other templates in your application.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Application</title>
</head>
<body>
<header>
<h1>Welcome to My Application</h1>
</header>
<main>
<!-- Content will be inserted here -->
<div>
{% block content %}{% endblock %}
</div>
</main>
<footer>
<p>© 2023 My Application</p>
</footer>
</body>
</html>

Creating a Child Template

Next, we'll create a child template that extends the base template. The child template will inherit the structure of the base template and can override specific blocks to insert its own content.

{% extends "base.html" %}
{% block content %}
<h2>Child Template Content</h2>
<p>This is the content of the child template.</p>
{% endblock %}

Using Template Inheritance in Views

In your Django views, you can render the child template just like any other template. Django will automatically use the base template and insert the content from the child template into the appropriate block.

from django.shortcuts import render

def my_view(request):
    return render(request, 'child.html')

Advanced Template Inheritance

You can create more complex inheritance structures by defining multiple blocks in your base template and overriding them in your child templates. This allows for greater flexibility and modularity.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Application</title>
</head>
<body>
<header>
<h1>Welcome to My Application</h1>
{% block header %}{% endblock %}
</header>
<main>
{% block content %}{% endblock %}
</main>
<footer>
{% block footer %}{% endblock %}
<p>© 2023 My Application</p>
</footer>
</body>
</html>
{% extends "base.html" %}
{% block header %}
<h2>Child Template Header</h2>
{% endblock %}
{% block content %}
<p>This is the content of the child template.</p>
{% endblock %}
{% block footer %}
<p>Custom Footer Content</p>
{% endblock %}

Conclusion

Template inheritance is a powerful feature in Django that allows you to create flexible and reusable templates. By defining a base template and extending it in child templates, you can maintain a consistent layout across your application and make your code more modular and maintainable.