Marco Bruggmann
Marco Bruggmann

Reputation: 625

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

Upvotes: 20

Views: 16130

Answers (2)

Garrett
Garrett

Reputation: 49768

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)

Upvotes: 19

goodnews john
goodnews john

Reputation: 423

This is answer is coming late, but for anynone having this issue, you could do it like so in base.jinja2

{%import 'arby/header.jinja2' as header%}

jinja should know the path to templates so specifying a file in a subfolder in templates should be easy as the folder/file.extension.

Note: coming from flask pespective

Upvotes: 1

Related Questions