Welcome to our comprehensive guide on Django's Template Includes (include)! In this lesson, we'll delve into this powerful feature that lets you reuse parts of your HTML templates, making your code cleaner, more manageable, and easier to maintain.
Let's get started!
In Django, Template Includes (often referred to as {% include %}) is a built-in template tag that allows you to insert one template into another at the point where the tag appears. It's a practical way to create a modular structure for your HTML templates, promoting code reusability and reducing redundancy.
Using Template Includes brings numerous benefits to your projects:
Now that we understand why Template Includes are important, let's create our first include!
base.html in your templates directory. This will serve as our base template that includes common elements.<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Django Project</title>
</head>
<body>
{% block content %}
<!-- This is where the included template will be rendered -->
{% endblock %}
<!-- Include your common elements here -->
{% include 'common/header.html' %}
{% include 'common/footer.html' %}
</body>
</html>In the above example, we've defined a content block where the included template will be rendered. We've also included our common header and footer templates.
header.html and footer.html in a new directory called common within your templates directory.<!-- common/header.html -->
<header>
<nav>
<!-- Your navigation menu goes here -->
</nav>
</header><!-- common/footer.html -->
<footer>
<p>Β© 2022 My Django Project</p>
</footer>blog_post.html, and use the base.html as the parent template.<!-- blog_post.html -->
{% extends 'base.html' %}
{% block content %}
<h1>My Blog Post</h1>
<p>This is the content of my blog post.</p>
{% endblock %}With this setup, when you render blog_post.html, Django will automatically include the header.html and footer.html templates within the content block defined in base.html.
Happy coding! π»π