jinja2 autoescape扩展无法正常工作

时间:2014-09-09 08:43:43

标签: python jinja2

我对Jinja2 autoescape有一个问题,这让我很生气。根据 文档,我做以下

import jinja2
env=jinja2.Environment(autoescape=True,extensions=['jinja2.ext.autoescape'])
tpl = jinja_env.template_class('{% autoescape false %}...{% endautoescape %}')

然而,python抛出以下异常:

File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 906, in __new__
  return env.from_string(source, template_class=cls)
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 841, in from_string
  return cls.from_code(self, self.compile(source), globals, None)
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 554, in compile
  self.handle_exception(exc_info, source_hint=source)
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 742, in handle_exception
  reraise(exc_type, exc_value, tb)
File "<unknown>", line 1, in template
jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'autoescape'.

但是,当我检查env.extensions字典时, 包含一个 jinja2.ext.AutoEscapeExtension对象和这个对象,有一个标签属性,其中 等于set(['autoescape'])。所以一切看起来都应该有效,但事实并非......

1 个答案:

答案 0 :(得分:1)

没关系,我没有阅读文档......我不应该使用env.template_class来获取模板,env.from_string。愚蠢的我......