liveBook · Manning

Autoescape tag

As explained in Django in Action

The Django autoescape tag controls whether automatic HTML escaping is enabled for a template block.

The autoescape tag controls HTML escaping for a template block. Django normally transforms characters such as <, >, and other HTML-sensitive data before rendering it. section 3.7

Use block-level control when a template needs a deliberate exception:

  • {% autoescape off %} disables automatic escaping until {% endautoescape %}. section 3.7
  • The safe filter, mark_safe(), and format_html() can mark rendered values as safe; use them only when the HTML is intended. section 3.7

Rendering escaped and unescaped instrument names

A value of <b>sax</b> renders as &lt;b&gt;sax&lt;/b&gt; normally, but appears as <b>sax</b> inside an autoescape-off block. The same experiment shows safe values such as drum<br/> and formatted big <i>bass</i> remaining HTML. section 3.7

I love the sound a {{ instrument }} makes.
A shiny {{ instrument | safe }} is good.

{% autoescape off %}
Don't put a {{ instrument }} too close to your ear.
{% endautoescape %}

Inspect the compact template showing ordinary interpolation, the safe filter, and an autoescape-off block. section 3.7

How Django in Action covers it

How deep it goes
Demonstrates default escaping, block syntax, safe values, and REPL output, without detailing the escaping implementation.
Examples
Uses instrument names including tuba > baritone, <b>sax</b>, drum<br/>, and formatted big <i>bass</i>.
What it assumes
Assumes basic template variables and HTML characters while demonstrating escaping through a loaded template and Context.
What you can do after
Apply it via Django template syntax to choose where a template block escapes or preserves HTML.
How it connects
Connects templates with HTML escaping, the safe filter, mark_safe(), format_html(), and Django’s template engine.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.