liveBook · Manning

Safe filter

As explained in Django in Action

The Django safe filter marks template output as trusted HTML so the value is not automatically escaped.

The safe filter tells Django that template output already contains trusted HTML, so automatic escaping does not turn tags into visible text. Use {{ value|safe }} when the value should render as HTML rather than appear as escaped characters. section 3.7

Rendering HTML in a template

With instrument set to <b>sax</b>, {{ instrument }} renders &lt;b&gt;sax&lt;/b&gt;, while {{ instrument|safe }} renders the bold sax text. The filter changes escaping behavior; it does not create the HTML.

Django also supports the escape filter and the autoescape tag. For dynamically built snippets, mark_safe() returns a SafeString, while format_html() constructs formatted HTML as a SafeString. section 3.7

How Django in Action covers it

How deep it goes
Explains escaping behavior through template output, contrasting the safe filter with escape and autoescape controls.
Examples
Demonstrates escaped instrument names, rendered bold tags, mark_safe() output, and format_html() output in the Django REPL.
What you can do after
Apply it via Django templates to render trusted HTML instead of automatically escaped text.
How it connects
Connects the safe filter with auto-escaping, the escape filter, the autoescape tag, SafeString, mark_safe(), and format_html().

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.