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
<p>You are <em>pretty</em> smart!</p>
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!
Warning: Always Escape User-entered Data
Never trust user-entered data. Only turn autoescaping off if you are sure the content is safe (i.e., you wrote it).
Commentary
Be careful with this!
Consider the following:
Variable
Template
Result
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.