I am using Google App Engine with Python/Jinja2
I have a few html content files, like content1.html, content2.html and content3.html. Each of them need to extend a base html file called base.html.
Suppose these 4 files are in the some folder, then at the beginning of the content files, I just need to put {% extends "base.html" %}, and the html files render well.
However, as my project grows, more and more pages have been created. I would like to organize the files by creating sub-folders. So now suppose in the root directory, I have the base.html and subfolder1. Inside subfolder1, I have content1.html.
In my python:
JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(os.path.dirname(__file__))+"\\subfolder1"))
template = JINJA_ENVIRONMENT.get_template("content1.html")
template.render({})
or
JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(os.path.dirname(__file__))))
template = JINJA_ENVIRONMENT.get_template("subfolder1\\content1.html")
template.render({})
But then in content1.html,
{% extends "????????" %}
what should put in the question marks to extend the base.html which is in the parent folder?
more clearly:
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'))
The folder templates
is now the template's root:
template = env.get_template('content.html') # /templates/content.html
self.response.write(template.render())
or using subfolders:
template = env.get_template('folder/content.html')
self.response.write(template.render())
in content.html:
{% extends "base.html" %} # /templates/base.html
{% extends "folder/base.html" %} # /templates/folder/base.html
Try this:
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(
[os.path.dirname(os.path.dirname(__file__)),
os.path.dirname(os.path.dirname(__file__)) + "/subfolder1"]))
then:
{% extends "base.html" %}
according this: http://jinja.pocoo.org/docs/api/#basics (class jinja2.FileSystemLoader(searchpath, encoding='utf-8'))
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