Flask/Jinja2 - Include template relative to current template

Viewed 1277

Is there a syntax for referencing a local file? For example

Instead of having to write :

{% include 'user/project/task/task_detail/tab.html' %}

I want to write (from a template that's in the same directory as tab.html):

{% include './tab.html' %}

But the above raises jinja2.exceptions.TemplateNotFound

2 Answers

You can subclass Jinja's Environment and override the join_path() method to support import paths relative to the current directory.

class RelativeEnvironment(jinja2.Environment):
    """Override join_path() to enable relative template paths."""
    def join_path(self, template, parent):
        return os.path.join(os.path.dirname(parent), template)

However please mind that Jinja's mechanism of finding templates is designed in order to disambiguate templates' paths.

You can read more at https://jinja.palletsprojects.com/en/2.10.x/api/#jinja2.Environment.join_path

This question is a possible duplicate of How to include a template with relative path in Jinja2

Flask/j2 needs to know the structure to find a file, and it knowns the basic structure of app subfolders (static, templates etc.). The best way is to put it in a static subfolders and then point at it using the url_for function:

..."{{ url_for('static', filename='<subfolder>/tab.html') }}"...
`
Related