Autoescaping

Autoescaping is a feature to mitigate injection attacks when renderingHTML and XML documents. When autoescaping is enabled, Jinja will useMarkupSafe to escape unsafe characters in the output of expressions,unless the output is marked safe. For example, if a comment contained<script>alert("hello")</script>, the tags would be rendered withescapes like &lt;script&gt;. In a user’s browser, the comment woulddisplay as text, rather than being interpreted as a script.

Because Jinja can be used to render any type of document for many typesof applications, not just HTML with untrusted input, autoescaping is notenabled by default. You should configure a sensible default based onyour use case when creating the environment. Theselect_autoescape() function can be used to enableautoescaping for HTML templates while disabling it in text templates.

  • jinja2.selectautoescape(_enabled_extensions=('html', 'htm', 'xml'), disabled_extensions=(), default_for_string=True, default=False)
  • Intelligently sets the initial value of autoescaping based on thefilename of the template. This is the recommended way to configureautoescaping if you do not want to write a custom function yourself.

If you want to enable it for all templates created from strings orfor all templates with .html and .xml extensions:

  1. from jinja2 import Environment, select_autoescape
  2. env = Environment(autoescape=select_autoescape(
  3. enabled_extensions=('html', 'xml'),
  4. default_for_string=True,
  5. ))

Example configuration to turn it on at all times except if the templateends with .txt:

  1. from jinja2 import Environment, select_autoescape
  2. env = Environment(autoescape=select_autoescape(
  3. disabled_extensions=('txt',),
  4. default_for_string=True,
  5. default=True,
  6. ))

The enabled_extensions is an iterable of all the extensions thatautoescaping should be enabled for. Likewise disabled_extensions isa list of all templates it should be disabled for. If a template isloaded from a string then the default from default_for_string is used.If nothing matches then the initial value of autoescaping is set to thevalue of default.

For security reasons this function operates case insensitive.

Changelog

New in version 2.9.

You can also pass autoescape=True to enable it unconditionally, orpass your own function that takes the name of the template and returnswhether it should be enabled. When writing a function, make sure toaccept None as a name, as that will be passed for string templates.

Inside a template the behaviour can be temporarily changed by usingthe autoescape block, see Autoescape Overrides.