autoescapeΒΆ
Whether automatic escaping is enabled or not, you can mark a section of a
template to be escaped or not by using the autoescape tag:
{% autoescape %}
Everything will be automatically escaped in this block
using the HTML strategy
{% endautoescape %}
{% autoescape 'html' %}
Everything will be automatically escaped in this block
using the HTML strategy
{% endautoescape %}
{% autoescape 'js' %}
Everything will be automatically escaped in this block
using the js escaping strategy
{% endautoescape %}
{% autoescape false %}
Everything will be outputted as is in this block
{% endautoescape %}
When automatic escaping is enabled everything is escaped by default except for values explicitly marked as safe. Those can be marked in the template by using the raw filter:
{% autoescape %}
{{ safe_value|raw }}
{% endautoescape %}
Functions returning template data (like macros and parent) always return safe markup.
Caution
A value marked as safe is output as-is, even inside a quoted HTML attribute value, where an HTML fragment can close the attribute. Read how to escape it there.
Note
Twig is smart enough to not escape an already escaped value by the escape filter when the automatic escaping strategy is the same as the one applied by the escape filter.
Note
Twig does not escape string literals printed directly, but it escapes variables, even when they were set to a literal:
{% set hello = "<strong>Hello</strong>" %}
{{ hello }}
{{ "<strong>world</strong>" }}
Will be rendered as:
<strong>Hello</strong>
<strong>world</strong>
Note
The chapter Twig for Developers gives more information about when and how automatic escaping is applied.