Search code examples
pythontemplatesincluderenderjinja2

How to include a template with relative path in Jinja2


I'm trying, in a template, to include another one that is in the same folder. To do so, i'm just doing {% import 'header.jinja2' %}. The problem is that i keep getting a TemplateNotFound error.

My template folder looks like

+ myProject
|
+--+ templates
   |
   +--+ arby
   |  |-- header.jinja2
   |  |-- footer.jinja2
   |  +-- base.jinja2
   |
   +--+ bico
      |-- header.jinja2
      |-- footer.jinja2
      +-- base.jinja2

So when I render arby's 'base.jinja2' I would like to include 'arby/header.jinja2' and when I render bico's 'base.jinja2' I would like to include 'bico/header.jinja2'. The thing is that I don't want to write the 'arby/' or 'bico/' prefix in the {% include 'arby/base.jinja2' %}. Is this possible?

Thanks


Solution

  • There is a hint in the jinja2.Environment.join_path() docstring about subclassing Environment and overriding the join_path() method to support import paths relative to the current (i.e., the parent argument of join_path) template.

    Here is an example of such a class:

    import posixpath
    class RelEnvironment(jinja2.Environment):
        """Override join_path() to enable relative template paths."""
        def join_path(self, template, parent):
            return posixpath.join(posixpath.dirname(parent), template)