【问题标题】:Python Google App Engine Jinja2 Can't find IncludePython Google App Engine Jinja2 找不到包含
【发布时间】:2013-09-23 13:37:56
【问题描述】:

我是谷歌应用引擎和 python 开发的新手,我正在尝试使用 Jinja2 作为我的模板引擎。我有一个试图“包含”页眉和页脚的页面,但我不断收到此错误:TemplateNotFound: base/header.html

我的代码如下。如果您有任何建议,请告诉我。

Python

JINJA_ENVIRONMENT = jinja2.Environment(
   loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
   extensions=['jinja2.ext.autoescape'])

class MainPage(webapp.RequestHandler):


    def get(self):
        template_values = {'title' : 'Test Value'}
        template = JINJA_ENVIRONMENT.get_template('/public/templates/index.html')
        self.response.write(template.render(template_values))

配置

libraries:
- name: webapp2
  version: latest
- name: jinja2
  version: latest

文件结构

- my application
  - public
    - scripts
    - stylesheets
    - templates
      - base
        - header.html
        - footer.html
      - index.html
  - app.yaml
  - myapplication.py

HTML (index.html)

{% include "base/header.html" %}
<nav class="top-bar" style="">
  <!-- more html here -->
</nav>
{% include "base/footer.html" %}

【问题讨论】:

    标签: python google-app-engine jinja2


    【解决方案1】:

    我没有使用 jinja2 的 loader 属性,所以我不确定这条线是做什么的

    loader=jinja2.FileSystemLoader(os.path.dirname(__file__))
    

    但我确实成功地将 App Engine 与 jinja2 一起使用,所以我想我可以提供帮助。我知道默认情况下 jinja2 在项目的根目录中查找名为“templates”的目录。因此对于 header.html,jinja2 会期望该文件位于“templates/base/header.html”中。

    如果你查看 environment.py,其中 get_template 函数用于 jinja2,如果抛出

        If the template does not exist a :exc:`TemplateNotFound` exception is
        raised.
    

    在您的应用引擎项目的根目录中创建一个模板目录,并将所有 jinja2 模板移动到那里,如果可以解决问题,请告诉我。当您将模板名称传递给 jinja2 时,它们都将与文件夹相关,因此调用应如下所示

    template = JINJA_ENVIRONMENT.get_template('index.html')
    

    index.html 位于根目录的 /templates/index.html 中。

    如果是这样,我可以向您展示如何通过将字典传递给它来自定义 jinja2 默认配置。

    【讨论】:

    • 如果这不起作用,请告诉我。我将使用应用引擎和 jinja2 提供我的设置配置的完整示例。
    • 非常感谢您的帮助!根据您的建议,我想我离得更近了。我现在将 loader 属性更改为: loader=jinja2.FileSystemLoader('templates/', 'templates/base/') 并将模板移动到根目录。我现在收到一个新错误:文件“/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/jinja2-2.6/jinja2/loaders.py”,第 169 行,在get_source contents = f.read().decode(self.encoding) LookupError: unknown encoding: templates/base/ 这些文件的编码是 UTF-8。
    • 该错误是由于 jinja2.FileSystemLoader('templates/', 'templates/base/') 中的第二个参数造成的。如果您查看 loaders.py 的源代码,构造函数将一个编码参数作为第二个参数。所以你说编码是'模板/基础'。我认为你应该删除它并保留 jinja2.FileSystemLoader('templates')。然后将 base 中的模板引用为“base/mytemplate.html”。让我知道情况如何。如果你愿意,如果我们不能让你工作,我仍然会提供我的设置。
    • 我刚刚注意到,如果您尝试为加载程序提供多个路径,则将数组传递给第一个参数。从他们的档案中。 FileSystemLoader(['/path/to/templates', '/other/path'])
    • 再次感谢您的帮助!似乎正在使用:jinja2.FileSystemLoader('templates')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    • 2023-03-25
    • 2019-07-10
    • 2017-07-19
    相关资源
    最近更新 更多