Inheriting templates

What is template inheritance?

Template inheritance in simple words means using one main template structure in all the files. 

For example : If we have a static part of the website which is the same in all the pages like navbar, footer,etc, Nobody would like to repeat the code in all the pages. Major problem is when you got a small change in the navbar you have to go to each page and change it. So Using templates we can write the navbar code in the main template and just extend that in all other files we want to use it.

How to inherit a main Template?

To inherit a template, we have to first create a file and let's name it maintemp.html. Write a basic html structure in the maintemp.html as shown below and add the block with the blockname in a tag "{% %}".

<html lang="en">
<head>
    <title>
        {% block title %}

        {% endblock title %}
    </title>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
          aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
          <ul class="navbar-nav ml-auto">
            <li class="nav-item active">
              <a class="nav-link" href="{% url '/' %}">Home <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="{% url 'add-prod' %}">Add Products</a>
            </li>         
            <li class="nav-item">
              <a class="nav-link" href="{% url 'login' %}">Login</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="{% url 'register' %}">Register</a>
            </li>
          </ul>
        </div>
      </nav>
{% block content %}

    {% endblock content %}

    {% block scripts %}
    
    {% endblock scripts %}
</body>
</html>

You can also use the url in the tag as shown in the above example.

Now when you create a new file, you don't have to repeat the html structure or the navbar, and other static codes. You can directly extend this template in the new pages you create as shown below.

{% extends 'accounts/maintemp.html' %}

{% block title %}
Funda of Web IT
{% endblock title %}

{% block content %}


<h1>Hello! This is my first template </h1>

{% endblock content %}


© Copyright - 2018 - 2021 | All rights reserved at Funda of Web IT