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
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 (ie, 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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.