谷歌App引擎WebApp中Jinja2自动转义问题

5 投票
1 回答
4214 浏览
提问于 2025-04-16 09:51

我决定安装jinja2来支持我的网页应用程序的自动转义功能。所以我在Python 2.5中安装了jinja2,并在我的项目中创建了一个符号链接,指向那个目录。大部分情况下都能正常工作。

但是,当我实际尝试使用{% 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)

再次强调,只要我不使用自动转义标签,它就能正常工作。

1 个回答

8

{% autoescape %} 标签需要使用 Jinja 2.4 版本或更高版本,并且需要加载 jinja2.ext.autoescape 这个扩展。

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

撰写回答