WARNING: You are browsing the documentation for Symfony 4.1 which is not maintained anymore. Consider upgrading your projects to Symfony 5.0.

How to Escape Output in Templates

4.1 version
Maintained Unmaintained

How to Escape Output in Templates


Hello {{ name }}

Imagine the user enters the following code for their name:







The Twig and PHP templating systems approach the problem in different ways. If you're using Twig, output escaping is on by default and you're protected. In PHP, output escaping is not automatic, meaning you'll need to manually escape where necessary.

Output Escaping in Twig

If you're using Twig templates, then output escaping is on by default. This means that you're protected out-of-the-box from the unintentional consequences of user-submitted code. By default, the output escaping assumes that content is being escaped for HTML output.

In some cases, you'll need to disable output escaping when you're rendering a variable that is trusted and contains markup that should not be escaped. Suppose that administrative users are able to write articles that contain HTML code. By default, Twig will escape the article body.

To render it normally, add the raw filter:

{{ article.body|raw }}


Output Escaping in PHP

Output escaping is not automatic when using PHP templates. This means that unless you explicitly choose to escape a variable, you're not protected. To use output escaping, use the special escape() view method:

Hello <?= $view->escape($name) ?>


var myMsg = 'Hello <?= $view->escape($name, 'js') ?>';
