How to Use Include in Django Template: Syntax and Examples
Use the
{% include 'template_name.html' %} tag in a Django template to insert another template's content. This helps reuse common HTML parts like headers or footers across pages.Syntax
The {% include %} tag inserts the content of another template file into the current template. You specify the file name as a string inside quotes.
Example parts:
{% include 'file.html' %}: Inserts the content offile.html.- The included template can access the current context variables.
django
{% include 'header.html' %}Example
This example shows how to include a header template inside a main template. The header template contains a simple navigation bar.
django
{# header.html #}
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about/">About</a></li>
</ul>
</nav>
{# main.html #}
<html>
<body>
{% include 'header.html' %}
<h1>Welcome to the site</h1>
<p>This is the main content.</p>
</body>
</html>Output
<html>
<body>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about/">About</a></li>
</ul>
</nav>
<h1>Welcome to the site</h1>
<p>This is the main content.</p>
</body>
</html>
Common Pitfalls
Common mistakes when using {% include %}:
- Forgetting quotes around the template name, e.g.,
{% include header.html %}is wrong; it must be{% include 'header.html' %}. - Including a template that does not exist causes a template error.
- Assuming included templates have isolated context; they share the current context unless you use
withoronly.
django
{# Wrong usage - missing quotes #}
{% include header.html %}
{# Correct usage #}
{% include 'header.html' %}Quick Reference
| Usage | Description |
|---|---|
| {% include 'file.html' %} | Insert content of 'file.html' with current context |
| {% include 'file.html' with var='value' %} | Include with extra variable 'var' set to 'value' |
| {% include 'file.html' only %} | Include with only the variables passed explicitly, ignoring current context |
Key Takeaways
Use {% include 'template.html' %} to reuse template parts easily.
Always put the template name in quotes inside the include tag.
Included templates share the current context by default.
Use 'with' or 'only' to control variables passed to included templates.
Missing or wrong template names cause errors during rendering.