0
0
Djangoframework~5 mins

Template includes for reusability in Django

Choose your learning style9 modes available
Introduction

Template includes let you reuse parts of your webpage easily. This saves time and keeps your code neat.

You want the same header on many pages.
You have a footer that stays the same everywhere.
You want to reuse a navigation menu on multiple pages.
You want to keep your templates clean by splitting big files.
You want to update one small part and see it change everywhere.
Syntax
Django
{% include 'template_name.html' %}
Use the {% include %} tag inside your Django template where you want to add the reusable part.
The included template can have its own HTML and Django template code.
Examples
This adds the content of header.html here.
Django
{% include 'header.html' %}
This adds the footer section from footer.html.
Django
{% include 'footer.html' %}
This inserts a navigation menu from menu.html.
Django
{% include 'menu.html' %}
Sample Program

This example shows a base template that includes a header and footer from separate files. This way, the header and footer can be reused on many pages.

Django
{# base.html #}
<html lang="en">
  <head>
    <title>My Site</title>
  </head>
  <body>
    {% include 'header.html' %}
    <main>
      <h1>Welcome to my site</h1>
      <p>This is the main content.</p>
    </main>
    {% include 'footer.html' %}
  </body>
</html>

{# header.html #}
<header>
  <nav>
    <ul>
      <li><a href="/">Home</a></li>
      <li><a href="/about/">About</a></li>
      <li><a href="/contact/">Contact</a></li>
    </ul>
  </nav>
</header>

{# footer.html #}
<footer>
  <p>© 2024 My Site. All rights reserved.</p>
</footer>
OutputSuccess
Important Notes

Included templates can also use variables passed from the parent template.

If the included file is missing, Django will raise an error unless you use the ignore missing option.

Summary

Use {% include %} to add reusable template parts.

This helps keep your templates clean and easy to update.

Common uses are headers, footers, and menus.