autoescape Tag

Coding

Argument(s): on or off

Documentation

When autoescaping is on, which is the default, all HTML tags in variables will be escaped.

The following code will turn autoescaping off on a block of content:

{% autoescape off %}
  Variables in this block will not be escaped.
{% endautoescape %}

Arguments

The autoescape tag takes one argument, which must be either “on” or “off”:

  • on (the default) – The HTML in all variables will be escaped using HTML entities.
  • off – The HTML will not be escaped.

As autoescaping is applied by default, you are most likely to use this tag to turn autoescaping off. It is useful, for example, if you are storing HTML in a database (e.g., for a blog article or a product description).

Variable

blurb = '<p>You are <em>pretty</em> smart!</p>'

Template

{{ blurb }}

Result

&lt;p&gt;You are &lt;em&gt;pretty&lt;/em&gt; smart!&lt;/p&gt;

The client (e.g., a browser) would then interpret was returned, so your users would see this HTML in the browser:

<p>You are <em>pretty</em> smart!</p>

The following code, on the other hand, would return unescaped HTML to the client:

Template

{% autoescape off %}
  {{ blurb }}
{% endautoescape %}

Result

<p>You are <em>pretty</em> smart!</p>

In this case, your users would see:

You are pretty smart!

Commentary

Be careful with this!

Consider the following:

Variable

blurb_dangerous = '<script>alert("Danger!");</script>'

Template

{% autoescape off %}
  {{ blurb_dangerous }}
{% endautoescape %}

Result

<script>alert("Danger!");</script>

An alternative, and often a better/safer approach, is to use the safe filter on each variable that you want to output without escaping. That method is only safer because it is more obvious which variables are being regarded as safe; however, it still carries with it the risk of a hacker injecting JavaScript into your web pages.

See Wikipedia for more information on Cross-site scripting.


Did we get something wrong? Is there a use case for the autoescape tag that we should add? Please let us know.

Send Feedback

Official Documentation
This page last updated on Sept. 16, 2020, 7:33 p.m. EST