【问题标题】:problem with jinja2 autoescape in google app engine webappgoogle app engine webapp中的jinja2 autoescape问题
【发布时间】:2011-06-08 03:27:54
【问题描述】:

我决定安装 jinja2 以与我的 webapp 应用程序一起使用,以支持自动转义功能。所以我将 jinja2 安装到 python 2.5 中,并在我的项目中创建了一个指向该目录的符号链接。它大部分工作正常。

除了,当我实际尝试使用 {% autoescape true %} 标记时,我收到消息:

File "/Users/me/project/templates/_base.html", line 1, in template
    {% autoescape true %}
TemplateSyntaxError: Encountered unknown tag 'autoescape'.

我正在使用文档中的标签:

{% autoescape true %} stuff {{var1}} stuff {{var2}}{% endautoescape %}

在我的处理程序文件中,我正在导入相关内容:

from jinja2 import Environment, FileSystemLoader, TemplateNotFound
from jinja2.ext import autoescape

并且导入工作正常,因为它没有引发错误。我做错了什么,还是 jinja2 本身有问题,比如在 ext.py 中?


更新: 我在下面尝试了 sharth 的建议并得到了相同的结果。这是我根据他的建议更新的处理程序。

class MainHandler(BaseHandler):
    def get(self):

        self.context['testEscape']='<script type="javascript">alert("hi");</script>'
        env = Environment(loader=FileSystemLoader([os.path.join(os.path.dirname(__file__), 'templates')]), autoescape=False)
        template = env.get_template('index.html')
        content = template.render(self.context)
        self.response.out.write(content)

同样,只要我不使用 autoescape 标签,它就可以正常工作。

【问题讨论】:

  • 我刚刚注意到 jinja2 自动完成标签也不能像 tipfy 框架中记录的那样工作。这让我认为这是 jinja2 中的一个错误,而不是我如何使用它的问题。

标签: python google-app-engine jinja2


【解决方案1】:

{% autoescape %} 标签需要 Jinja 2.4 或更高版本并加载了 jinja2.ext.autoescape 扩展。

env = Environment(autoescape=True, extensions=['jinja2.ext.autoescape'],
                  loader=...)

【讨论】:

  • 谢谢。我原以为我可以在脚本顶部使用 import 语句导入扩展,但没有意识到在实例化环境时需要将扩展​​设置为参数。我想标题为“添加扩展”的扩展文档(jinja.pocoo.org/extensions)顶部的段落应该是一个死的赠品。 :-)
  • 其实autoescape是什么意思,为什么要用?
猜你喜欢
  • 2011-01-22
  • 1970-01-01
  • 2011-03-06
  • 2012-08-17
  • 2012-07-31
  • 1970-01-01
  • 1970-01-01
  • 2011-09-08
  • 1970-01-01
相关资源
最近更新 更多