谷歌应用引擎使用Jinja2模板从父文件夹扩展基础模板

7

我正在使用Python/Jinja2与Google App Engine。

我有几个HTML内容文件,例如content1.html、content2.html和content3.html。每个文件都需要扩展名为base.html的基本HTML文件。

假设这些4个文件在同一个文件夹中,那么在内容文件的开头,我只需要放置{% extends "base.html" %},然后HTML文件就可以正常渲染。

然而,随着我的项目越来越大,越来越多的页面被创建。我想通过创建子文件夹来组织文件。所以现在假设在根目录中,我有base.html和subfolder1。在subfolder1中,我有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({})

或者
JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(os.path.dirname(__file__))))
template = JINJA_ENVIRONMENT.get_template("subfolder1\\content1.html")
template.render({})

但是在content1.html中,
{% extends "????????" %}

如何在子文件夹中扩展父文件夹中的base.html?请将问号处填入正确的内容。

2个回答

10

更加清晰明了:

from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'))

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

template = env.get_template('content.html') # /templates/content.html
self.response.write(template.render())

或者使用子文件夹:

template = env.get_template('folder/content.html')
self.response.write(template.render())

在content.html中:

{% extends "base.html" %}        # /templates/base.html
{% extends "folder/base.html" %} # /templates/folder/base.html

6
尝试一下这个:
JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(
        [os.path.dirname(os.path.dirname(__file__)),
         os.path.dirname(os.path.dirname(__file__)) + "/subfolder1"]))

然后:
{% extends "base.html" %}

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接