4 .. versionadded:: 1.9.0
5 The ``css``, ``url``, and ``html_attr`` strategies were added in Twig
8 .. versionadded:: 1.14.0
9 The ability to define custom escapers was added in Twig 1.14.0.
11 The ``escape`` filter escapes a string for safe insertion into the final
12 output. It supports different escaping strategies depending on the template
15 By default, it uses the HTML escaping strategy:
19 {{ user.username|escape }}
21 For convenience, the ``e`` filter is defined as an alias:
27 The ``escape`` filter can also be used in other contexts than HTML thanks to
28 an optional argument which defines the escaping strategy to use:
33 {# is equivalent to #}
34 {{ user.username|e('html') }}
36 And here is how to escape variables included in JavaScript code:
40 {{ user.username|escape('js') }}
41 {{ user.username|e('js') }}
43 The ``escape`` filter supports the following escaping strategies:
45 * ``html``: escapes a string for the **HTML body** context.
47 * ``js``: escapes a string for the **JavaScript context**.
49 * ``css``: escapes a string for the **CSS context**. CSS escaping can be
50 applied to any string being inserted into CSS and escapes everything except
53 * ``url``: escapes a string for the **URI or parameter contexts**. This should
54 not be used to escape an entire URI; only a subcomponent being inserted.
56 * ``html_attr``: escapes a string for the **HTML attribute** context.
60 Internally, ``escape`` uses the PHP native `htmlspecialchars`_ function
61 for the HTML escaping strategy.
65 When using automatic escaping, Twig tries to not double-escape a variable
66 when the automatic escaping strategy is the same as the one applied by the
67 escape filter; but that does not work when using a variable as the
72 {% set strategy = 'html' %}
74 {% autoescape 'html' %}
75 {{ var|escape('html') }} {# won't be double-escaped #}
76 {{ var|escape(strategy) }} {# will be double-escaped #}
79 When using a variable as the escaping strategy, you should disable
84 {% set strategy = 'html' %}
86 {% autoescape 'html' %}
87 {{ var|escape(strategy)|raw }} {# won't be double-escaped #}
93 You can define custom escapers by calling the ``setEscaper()`` method on the
94 ``core`` extension instance. The first argument is the escaper name (to be
95 used in the ``escape`` call) and the second one must be a valid PHP callable:
99 $twig = new Twig_Environment($loader);
100 $twig->getExtension('Twig_Extension_Core')->setEscaper('csv', 'csv_escaper');
103 $twig->getExtension('core')->setEscaper('csv', 'csv_escaper');
105 When called by Twig, the callable receives the Twig environment instance, the
106 string to escape, and the charset.
110 Built-in escapers cannot be overridden mainly they should be considered as
111 the final implementation and also for better performance.
116 * ``strategy``: The escaping strategy
117 * ``charset``: The string charset
119 .. _`htmlspecialchars`: http://php.net/htmlspecialchars