Jinja: Multiple Templates Reuse and Inclusion
n
The include tag is not limited to a single template. You can provide a list of templates, and Jinja2 will try to render each one in order until it finds a template that exists. This is an incredibly useful feature for creating fallbacks or handling specific cases, such as rendering a detailed version of a page if it exists, otherwise falling back to a generic one.
nn
How It Works
n
When you provide a list of template paths, Jinja2 iterates through the list from left to right. The first template that is found and is not missing will be rendered and inserted into the current template. All subsequent templates in the list will be ignored. This allows you to set up a priority list for your template includes.
nn
nn
Code Demonstration
n
Let’s see some examples of how to include multiple templates. First, the basic usage with a simple fallback.
nn
Basic Usage with Fallback
n
{% include ['page_detailed.html', 'page.html'] %}
n
In this example, if page_detailed.html exists, it will be rendered. If not, Jinja2 will fall back to rendering page.html.
nn
Combined with ignore missing
n
You can also combine this with the ignore missing keyword to gracefully handle a situation where none of the templates in the list exist. This prevents the entire page from crashing.
nn
{% include ['special_sidebar.html', 'sidebar.html'] ignore missing %}
n
Here, the engine will first look for special_sidebar.html. If it doesn’t exist, it will look for sidebar.html. If neither is found, the statement will be ignored and no error will be raised.
nn
Using a Variable
n
You can even pass a variable that holds a template name or an object with a template attribute to the statement.
nn
{% set my_template_list = ['user_info.html', 'default_info.html'] %}n{% include my_template_list %}
n
This provides maximum flexibility, allowing you to dynamically determine which templates to include based on your application’s logic.
nn
n
