Django Tutorial 5: Understanding Template Inheritance in Django

Posted by

Django – Template Inheritance || Tutorial 5

Django – Template Inheritance || Tutorial 5

In this tutorial, we will be learning about template inheritance in Django. Template inheritance allows you to create a base or parent template and then extend that template for different pages.

Creating a Base Template

To create a base template, you simply create a new HTML file and define the structure of your base template. For example:

{% block title %}My Website{% endblock %}

{% block content %}

This is the parent template.

{% endblock %}

In the above example, we have created a base template with a title block and a content block. These blocks will be used to extend the template in our child templates.

Extending the Base Template

Now, let’s create a child template that extends our base template. For example:


{% extends "base.html" %}

{% block title %}
About Us
{% endblock %}

{% block content %}

About Us

Welcome to our website!

{% endblock %}

In the above example, we have used the “extends” tag to extend the base template. We have also defined the title and content blocks to override the blocks in the base template.

Conclusion

Template inheritance is a powerful feature in Django that allows you to create reusable templates and easily manage the layout of your website. By creating a base template and extending it for different pages, you can save time and maintain a consistent look and feel across your site. We hope this tutorial has helped you understand the basics of template inheritance in Django.

0 0 votes
Article Rating
5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@user-id5ch3qy4m
6 months ago

help very well🎉

@aishwaryapathak6016
6 months ago

Full support 💪

@aishwaryapathak6016
6 months ago

Keep it up bro..

@kamalaggarwal3937
6 months ago

Insane

@lakshay6012
6 months ago

This guy is a saviour