Jinja: The include Statement
n
The include tag is used to render another template and insert the output directly into the current template. This is a very common and effective way to reuse common page components such as headers, footers, or sidebars. It allows you to break down a single webpage into smaller, more manageable template files, which greatly improves the organization and maintainability of your project.
nn
How It Works
n
The syntax for including a template is straightforward: you simply use {% include 'path/to/template.html' %}. When the template engine encounters this tag, it will render the specified template file and embed the resulting HTML in its place. The included template has access to the context (the variables and data) of the current template by default.
nn
Basic Usage
n
{% include 'header.html' %}n<main>n Body goes here.n</main>n{% include 'footer.html' %}
n
This example demonstrates how you can compose a full HTML page by including separate header.html and footer.html files. The content inside the main tag will be placed between the rendered header and footer.
nn
nn
Context Behavior
n
By default, an included template has full access to the variables from the parent template’s context. This is the with context behavior. However, if you want the included template to be completely isolated and not have access to the parent’s variables, you can use the without context keyword.
nn
Example with and without context
n
{# The default behavior: 'user' is accessible in the included template #}n{% include 'user_info.html' %}nn{# This will render the template in a separate context #}n{% include 'user_info.html' without context %}
n
Using `without context` is useful for reusable components that should not rely on the parent template’s data, making them more portable and less prone to unexpected behavior. For more complex context behavior, you can also pass specific variables using the with keyword, such as {% include 'user_info.html' with user=current_user %}.
nn
n
n
