【问题标题】:Cause of jinja2.exceptions.TemplateNotFound even when using just jinja2jinja2.exceptions.TemplateNotFound 的原因,即使只使用 jinja2
【发布时间】:2016-03-31 20:39:08
【问题描述】:

问题的原因事后很明显,但我想在这里分享不太明显的原因。

运行代码时如

import jinja2

templateLoader = jinja2.FileSystemLoader(searchpath=".")
templateEnv = jinja2.Environment(loader=templateLoader,
                                 trim_blocks=True,
                                 lstrip_blocks=True)

htmlTemplateFile = 'file.jinja.html'
htmlTemplate = templateEnv.get_template(htmlTemplateFile)

如果你遇到这个问题:

Traceback (most recent call last):
    ...
  File "file.py", line xyz, in some_func
    htmlTemplate = templateEnv.get_template(htmlTemplateFile)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/jinja2/environment.py", line 812, in get_template
    return self._load_template(name, self.make_globals(globals))
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/jinja2/environment.py", line 774, in _load_template
    cache_key = self.loader.get_source(self, name)[1]
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/jinja2/loaders.py", line 187, in get_source
    raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: file.jinja.html

你可能会发现网上的讨论表明这个问题一定与jinja2与flaskGAEPyramidSQL的交互有关,而且可能确实是这样您的模板不在“模板”文件夹中,但这个问题可能是由jinja2os 模块的交互引起的。

【问题讨论】:

    标签: jinja2


    【解决方案1】:

    罪魁祸首正在改变当前目录,例如,

    import os
    os.chdir(someDir)
    

    如果 templateEnv.get_template(...) 在此之后被调用,jinja2 将在“当前”目录中查找模板,即使该目录已更改。

    由于模块 os 提供 os.chdir 但不提供 os.pushdir/os.popdir,因此必须模拟后一对或完全避免 chdir。

    【讨论】:

      猜你喜欢
      • 2020-03-20
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      • 2016-09-24
      • 2017-11-03
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      相关资源
      最近更新 更多