This tutorial aims to provide a comprehensive understanding of template inheritance in Django. By the end of this tutorial, you will learn how to create a base template and extend it in child templates.
A basic understanding of Django, Python, and HTML is required. Familiarity with Django's templating language will be helpful.
Template inheritance is a feature in Django's templating system that allows you to build a base "skeleton" template that contains all the common elements of your site, and then extend it in child templates for different parts of your site.
A base template usually contains elements like the site title, navigation bar, footer etc. Here's an example:
<!-- base.html -->
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<header>
<!-- navigation bar -->
</header>
<main>
{% block content %}
{% endblock %}
</main>
<footer>
<!-- footer -->
</footer>
</body>
</html>
In this example, {% block title %}{% endblock %}
and {% block content %}{% endblock %}
are placeholders for content that will be filled in by child templates.
To extend a base template, we use the {% extends "base.html" %}
tag at the top of the child template. Here's an example:
<!-- home.html -->
{% extends "base.html" %}
{% block title %}
Home Page
{% endblock %}
{% block content %}
<p>Welcome to the Home Page!</p>
{% endblock %}
In this example, the {% block title %}
and {% block content %}
tags in the base template are replaced with the content in the child template.
Here are some more practical examples:
<!-- about.html -->
{% extends "base.html" %}
{% block title %}
About Page
{% endblock %}
{% block content %}
<p>Welcome to the About Page!</p>
{% endblock %}
<!-- base.html -->
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<header>
<!-- navigation bar -->
</header>
<main>
{% block content1 %}
{% endblock %}
{% block content2 %}
{% endblock %}
</main>
<footer>
<!-- footer -->
</footer>
</body>
</html>
<!-- home.html -->
{% extends "base.html" %}
{% block title %}
Home Page
{% endblock %}
{% block content1 %}
<p>Welcome to the Home Page!</p>
{% endblock %}
{% block content2 %}
<p>Enjoy your stay.</p>
{% endblock %}
In this tutorial, we've learned about template inheritance in Django, how to create a base template, and extend it in child templates. This promotes code reuse and consistency across your site.
Create a base template with a navigation bar, main content area, and footer. Then create three child templates (Home, About, Contact) that extend the base template.
Modify the base template from Exercise 1 to include a sidebar content block. Extend this new base template in a child template.
Create a base template with two content blocks. Then create a child template that only fills one of the content blocks.
For further practice, try extending these exercises by adding more content blocks, more child templates, or more complex HTML structures.