One of the most powerful features of Django is its ability to reuse code dynamically. Template inheritance allows sharing of code between parent and child templates. It greatly reduces duplication of effort.

Django has its template language designed to blend with HTML. You will find it easy to work with Django's templates if you've worked with HTML code before. Other text-based template languages like Smarty or Jinja2 have similar syntax.

Let's learn more about template inheritance by building a Django project.

What's a Django Template?

In Django, a template is a text file that can generate any text-based format, such as HTML, XML, or CSV.

Django template tags control the logic enclosing variables and values in the template. The tags help to separate program logic from template presentation. They also help to keep your templates clean and organized.

Django has many built-in tags, which look like {% tag %}. Tags are helpful in many ways. They can create text in the output, perform loops, and load information into the template.

You will be using tags in this project to demonstrate template inheritance.

Create a Django Project

To get started, create a Django project. Create an app named templates. Once you've done so, you're ready to create a view function for the app, a URL path, and templates to demonstrate template inheritance.

Create a View Function

First, create a view function that renders the templates. In this case, you will render the index.html template. Import the render method from Django shortcuts. Then create a view function named index that returns and renders the index template.

        from django.shortcuts import render\n# Create your views here.\ndef index(request):\n     return render (request,'index.html')
    

Create a URL Path

Next, create a URL path for the view function to display the templates. Import the path function from django.urls and the view function from views.py file. Then import settings and static to render any images and media you may have in the templates.

        from django.urls import path\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nurlpatterns=[\n  path('',views.index,name='index'),\n]\nif settings.DEBUG:\n   urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

Create Templates

Now that you have the view and URL path, create the templates. To demonstrate template inheritance, create a base.html as a parent template. The base.html file will have general elements you wish to share with index.html, the child template.

        {% load bootstrap5 %}\n{% load static %}\n<!DOCTYPE html>\n<html lang="en">\n<head> \n   <meta charset="UTF-8">\n   <meta http-equiv="X-UA-Compatible" content="IE=edge">\n   <meta name="viewport" content="width=device-width, initial-scale=1.0">\n   <!-- titles -->\n   {% if title %}\n   <title> Inherited Templates {{title}}</title>\n   {% else %}\n   <title> Inherited Templates </title>\n   {% endif %}\n   {% block styles %}\n   {% bootstrap_css %}\n   <link rel="stylesheet" href="{% static 'css/style.css' %}">\n   {% endblock %}\n</head>\n<body>\n   {% include 'navbar.html' %}\n   {% block content %} {% endblock %}\n   <!-- Bootstrap links -->\n   <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">  </script>\n</body>\n</html>
    

First, load the Bootstrap and static dependencies onto the base.html template. You can use the Bootstrap framework with your Django project to style the HTML pages. The static dependency loaded at the top will load assets included in the static folder.

Django templates allow you to pass bits of logic responsible for displaying content. Template tags consist of text surrounded by "{%" and "%}" characters. The if/else statement checks for conditions in the view function. If the condition is true it renders the content in the first block; if false, it will render the content in the second.

The base.html file will also render the contents of navbar.html right where you place the template tags. That means whenever you extend the base.html, navbar.html is also inherited. Any template extending the base.html will inherit any element with an {% include %} tag.

Any text surrounded by {{}} is a template variable. Template variables are dynamic data provided by view functions. Django also uses block tags that use an open tag, like {% block content %}, and a closing tag, like {% endblock %}.

Block tags allow the child templates to override the contents of the parent templates. In this case, the index.html can replace its contents in the area enclosed by block tags. It will not interfere with the other base.html components.

Let's apply the logic to the index.html

        {% extends 'base.html' %}\n{% block content %}\n<div class="container text-center" style="color: white">\n    <h1>I Am The Index Template</h1>\n    <p>I inherited Bootstrap and the navbar from base.html</p>\n</div>\n{% endblock %}\n
    

In the index.html template, use the {% extend %} tag to extend components of the base.html. Inside the block tags {% block content %}, write all your code.

In the index.html template, you have an H1 and a paragraph element. You can use the template tags inside the divs to call variables from the view function.

Test Template Inheritance in the Browser

You can now run the server. Once you've done so, check in the browser to see whether the index.html file inherited the elements of base.html. That includes Bootstrap links and the navbar.html template.

index.html  with navbar from base.html

The index.html file should inherit the navbar and Bootstrap styles from the base template. If so, you have used template inheritance correctly. Without it, you would have had to add the navigation bar and Bootstrap links where you needed them.

Also, any changes you make to the base.html will reflect across all the templates it extends to. This principle is important in error handling. You can easily Identify templates with bugs.

Template inheritance is one of the many ways Django implements the Don't Repeat Yourself (DRY) principle. It will make your development much easier and simpler.

Why You Should Use Django Template Inheritance

Django's template inheritance is one of its most complex features. It may take some time to understand it, but once you do, it saves a lot of development effort.

Template inheritance allows you to share code between parent and child templates. This ensures you don't write repetitive code in your templates.

Template inheritance is important in large Django projects. In such cases, there are many applications and many templates to design. The parent templates give you lots of control over the application's other components.

By learning the Django template system, you can enjoy writing clean and powerful code.