Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 555
Marco Bruggmann Avatar asked Dec 14 '11 22:12

Marco Bruggmann


People also ask

How do I set variables in Jinja2?

How do you set variables in Jinja? {{ }} tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %} template tag and then assign the value the same way you would in normal python code.

How do you escape Jinja template?

Jinja Escaping Methods ¶Use the escape filter on variables which may contain unwanted HTML. Enable auto-escaping for the entire template by wrapping its content in auto-escape tags.


2 Answers

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:

class RelEnvironment(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)
like image 94
Garrett Avatar answered Oct 05 '22 06:10

Garrett


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

like image 29
goodnews john Avatar answered Oct 05 '22 06:10

goodnews john