Google App Engine Jinja2模板从父文件夹扩展基本模板

sha*_*716 5 python google-app-engine jinja2

我正在使用带有Python/Jinja2的Google App Engine

我有几个html内容文件,如content1.html,content2.html和content3.html.他们每个人都需要扩展一个名为base.html的基本html文件.

假设这4个文件在某个文件夹中,那么在内容文件的开头,我只需要放置{%extends"base.html"%},并且html文件渲染得很好.

但是,随着项目的增长,已经创建了越来越多的页面.我想通过创建子文件夹来组织文件.所以现在假设在根目录中,我有base.html和subfolder1.在子文件夹1中,我有content1.html.

在我的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({})
Run Code Online (Sandbox Code Playgroud)

要么

JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(os.path.dirname(__file__))))
template = JINJA_ENVIRONMENT.get_template("subfolder1\\content1.html")
template.render({})
Run Code Online (Sandbox Code Playgroud)

但是在content1.html中,

{% extends "????????" %}
Run Code Online (Sandbox Code Playgroud)

什么应该放在问号上以扩展父文件夹中的base.html?

Gio*_*oia 9

更清楚:

from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'))
Run Code Online (Sandbox Code Playgroud)

该文件夹templates现在是模板的根目录:

template = env.get_template('content.html') # /templates/content.html
self.response.write(template.render())
Run Code Online (Sandbox Code Playgroud)

或使用子文件夹:

template = env.get_template('folder/content.html')
self.response.write(template.render())
Run Code Online (Sandbox Code Playgroud)

在content.html中:

{% extends "base.html" %}        # /templates/base.html
{% extends "folder/base.html" %} # /templates/folder/base.html
Run Code Online (Sandbox Code Playgroud)


小智 5

试试这个:

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(
        [os.path.dirname(os.path.dirname(__file__)),
         os.path.dirname(os.path.dirname(__file__)) + "/subfolder1"]))
Run Code Online (Sandbox Code Playgroud)

然后:

{% extends "base.html" %}
Run Code Online (Sandbox Code Playgroud)

根据这个: http://jinja.pocoo.org/docs/api/#basics(类jinja2.FileSystemLoader(searchpath,encoding ='utf-8'))