Django - Extending HTML Templates

In the last tutorial, we added the bootstrap theme in our Django application. In any dynamic web app, we configure header, footer, and sidebars in base theme file so that whenever we need we can extend that file and use it within multiple HTML files as extend or as an import. 

In the theme which we used in our last tutorial, we have a file called blank.html which I will use as a base theme file as it has a header, footer, and sidebar with the menu.

Step 1: Find code which needs block

To extend an HTML file in the Django first we need to find the exact code which we need to be in the block. In this theme, we will put whatever is in the frame as mentioned in the below image in a block. That block can be used in other extended HTML files.

If we look that in code of blank.html it will be at:

        <!-- Begin Page Content -->
        <div class="container-fluid">

          <!-- Page Heading -->
          <h1 class="h3 mb-4 text-gray-800">Blank Page</h1>

        </div>
        <!-- /.container-fluid -->

Simply replace that code between div as a block section.

        <!-- Begin Page Content -->
        <div class="container-fluid">
{% block Page_section %}


{% endblock %}
        </div>

A Block defines code section which can be used in other extended HTML files.

Step 2: Create and Extended HTML file.

Simply create an extended HTML file with the below code to use block. Use load static if you need the static parameter for any block. 

{% extends 'blank.html' %}
{% load static %}

{% block Page_section %}

<p> Your HTML code goes here.. for this block..  </p>

{% endblock %}

Save this file as 'home.html' or any other name you want.

The above code extends your blank.html file and replaces block named 'Page_section' with code defined in this HTML file. You can use as many block sections as you want in your base theme.. 

Step 3: Use this new HTML file in your view.

Use this new HTML file in your view instead of blank.html.. 

 

 

 

I have added a video for more information on this 

About the author

akarperiwal

0 Comments

Please login to comment