94 words
1 minute
Turning on Jinja autoescaping when using Template() directly
Anubhav Gain
2024-05-12

Turning on Jinja autoescaping when using Template() directly#

Jinja autoescaping is turned off by default. Coming from Django this frequently catches me out.

You can turn on autoescaping for your Jinja environment using:

from jinja2 import Environment, FileSystemLoader
env = Environment(
loader=FileSystemLoader("/path/to/templates"),
autoescape=True
)

But what about if you are using Template directly? TIL that the Template class takes all of the same options as Environment does, so you can do this:

from jinja2 import Template
template = Template("""
<p>Hello {{ name }}</p>
""", autoescape=True)
print(template.render({"name": "Simon & Cleo"}))
# Output: <p>Hello Simon &amp; Cleo</p>

Here’s the Template class constructor.

Turning on Jinja autoescaping when using Template() directly
https://mranv.pages.dev/posts/turning-on-jinja-autoescaping-when-using-template-directly/
Author
Anubhav Gain
Published at
2024-05-12
License
CC BY-NC-SA 4.0