.. code-block:: jinja
- {% autoescape true js %}
- {{ var|escape('html') }} {# will be escaped for html and javascript #}
- {{ var }} {# will be escaped for javascript #}
- {{ var|escape('js') }} {# won't be double-escaped #}
+ {% autoescape 'js' %}
+ {{ var|escape('html') }} {# will be escaped for html and javascript #}
+ {{ var }} {# will be escaped for javascript #}
+ {{ var|escape('js') }} {# won't be double-escaped #}
{% endautoescape %}
.. note::
Internally, ``escape`` uses the PHP native `htmlspecialchars`_ function
for the HTML escaping strategy.
+.. caution::
+
+ When using automatic escaping, Twig tries to not double-escape a variable
+ when the automatic escaping strategy is the same as the one applied by the
+ escape filter; but that does not work when using a variable as the
+ escaping strategy:
+
+ .. code-block:: jinja
+
+ {% set strategy = 'html' %}
+
+ {% autoescape 'html' %}
+ {{ var|escape('html') }} {# won't be double-escaped #}
+ {{ var|escape(strategy) }} {# will be double-escaped #}
+ {% endautoescape %}
+
+ When using a variable as the escaping strategy, you should disable
+ automatic escaping::
+
+ .. code-block:: jinja
+
+ {% set strategy = 'html' %}
+
+ {% autoescape 'html' %}
+ {{ var|escape(strategy)|raw }} {# won't be double-escaped #}
+ {% endautoescape %}
+
.. _`htmlspecialchars`: http://php.net/htmlspecialchars