Teaching Main Template in mini-learn

django add master template
10 November 2024

In web design using the Django framework, one of the important and fundamental stages is utilizing the main templates. The main template allows you to define your shared and stable sections across your website in a separate file and use the same codes in different pages to avoid repetition.

For example, the header and footer are usually the same across each web page. By using the main templates, you can save these components in a single file and simply use them in other pages. In this way, all your pages can follow a single template layout, and if you need to make changes to the overall structure, it is sufficient to make changes only in the main template file.

In Django, this capability is achievable through template inheritance. In this section, I will review adding the main template in Django with a simple example.

To start, first create an HTML file with the overall structure of your page as the main template. This file can include the header, sidebar, and footer. In this file, use various blocks to reserve specific content areas for different pages.

Then, from the main template file, you can use different HTML files for the specific content of each page in predefined areas.


<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Main Page</title>
</head>
<body>
    <header>
        <h1>My Site</h1>
    </header>
    <nav>
        <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/about">About Us</a></li>
        </ul>
    </nav>
    <main>
        {% block content %}{% endblock %}
    </main>
    <footer>© 2023 My Site</footer>
</body>
</html>

The file base.html shown above defines the overall structure of the website. We’ve used the <header> tag to display the header and with the help of the <nav> tag to create the sidebar. The <main> section has a block that defines the content area that will contain specific content for each page.


The page header is marked with the <header> tag, and the title of the site is displayed here. This uses the <h1> tag to represent the main title of the site.


The sidebar is created with the <nav> tag and list items are created with <ul> and <li> tags. Links to various pages of the site are utilized with the <a> tag in the list.


The main section of each page is defined by the <main> tag which details that the block content is described in it and the specific content and variables for each page are added through this section.


In summary, the footer section with the <footer> tag appears at the end of the file that contains copyright information for the site.

FAQ

?

Why should we use the main template?

?

How can I create separate templates?

?

Can I use different sections in the main template?