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
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.
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With