Creating a Master Page in Django
Master Page is a feature in Django that makes it easy to add common content to multiple pages, such as headers and footers. Here we are going to learn how to add master page to our website.
Step 1
Create a file master.html in templates folder and add the common content in it
After that blocks need to be added as placeholders to give different content to each page.
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'mystyle.css' %}">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
<a href="/contact">Contact</a>
</nav>
{% block content %}{% endblock %}
<script src="{% static 'myscript.js' %}"></script>
</body>
</html>
Step 2
Remove the common content from index.html and add the blocks
{% extends 'master.html' %}
{% load static %}
{% block title %}
Home Page
{% endblock %}
{% block content %}
<h1 id="demo">Home</h1>
<img src="{% static 'image.jpg' %}" alt="">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Obcaecati error
iusto quos veritatis tenetur eveniet totam cum neque quas voluptatibus quod dicta,
pariatur exercitationem sit perferendis reprehenderit ea fugit voluptatum.</p>
{% endblock %}
Step 3
Make the same changes in about page as given below
{% extends 'master.html' %}
{% load static %}
{% block title %}
About Page
{% endblock %}
{% block content %}
<h1>About Us</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Obcaecati error
iusto quos veritatis tenetur eveniet totam cum neque quas voluptatibus quod dicta,
pariatur exercitationem sit perferendis reprehenderit ea fugit voluptatum.</p>
{% endblock %}
Step 4
Make the same changes in contact page as given below
{% extends 'master.html' %}
{% load static %}
{% block title %}
Contact Page
{% endblock %}
{% block content %}
<h1>Contact Us</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Obcaecati error
iusto quos veritatis tenetur eveniet totam cum neque quas voluptatibus quod dicta,
pariatur exercitationem sit perferendis reprehenderit ea fugit voluptatum.</p>
{% endblock %}
Step 5
After connecting to the master page, the home page will look like this
Step 6
As it is connected to the master page, styles and links are also added to the About page
Step 7
Similarly, if you open the contact page, you will see this