Can't disable the autoescape in jinja2

2019-04-04 05:16发布

问题:

In GAE I use jinja2 with the autoescape, and everything works well.

import jinja2
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True)

In one template I don't want the autoescape, so I tried to disable it like this:

{% autoescape false %}
{{content}}
{% endautoescape %}

When it's time to render this template I get the message Encountered unknown tag 'autoescape'.

回答1:

Try this:

{{ content | safe}}

docs:

  • Flask — Controlling Autoescaping
  • Jinja2 — Filters — safe


回答2:

In order for the autoescape tag to be recognized, you need to enable the autoescape extension when setting up jinja2, like this:

jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
                               autoescape = True,
                               extensions = ['jinja2.ext.autoescape'])

Also, make sure you're using jinja2 version 2.4 or higher in your app.yaml (the current version is GAE is 2.6):

libraries:
- name: jinja2
  version: "2.6"

For more information, see the documentation for the autoescape extension.