Jinja Include: Handling Missing Templates
n
By default, if an include statement references a template that does not exist, Jinja2 will raise an exception and your page will fail to render. This is the desired behavior for crucial parts of a page, such as a header or navigation bar. However, for optional components like a sidebar or a widget, you can use the ignore missing keyword to gracefully handle the situation and prevent the entire page from crashing.
nn
How It Works
n
When you add ignore missing to your include statement, Jinja2 will simply ignore the statement and continue rendering the rest of the template if the specified file cannot be found. This allows you to create more flexible layouts where optional components can be included without requiring the template file to be present. The ignore missing keyword must be placed before a context visibility statement, like with context or without context.
nn
nn
Code Demonstration
n
Here are a few examples of how to use ignore missing with various include statements. Let’s imagine we are trying to include an optional sidebar.html template.
nn
Basic Usage
n
{# If sidebar.html does not exist, the template will not render this line #} {% include "sidebar.html" ignore missing %}
n
With Context Keywords
n
{# Using `ignore missing` with both context options #}n{% include "sidebar.html" ignore missing with context %}n{% include "sidebar.html" ignore missing without context %}
n
As shown above, `ignore missing` always comes first. This allows you to combine it with the context behavior you need, giving you fine-grained control over how your template handles missing files.
nn
n
n
