Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable autoescaping in Twig using Symfony

Tags:

php

twig

symfony

I'm using Twig in my Symfony project.

Symfony should enable autoescape by default. However it doesn't do this by default and after I enable it by hand it still won't work.

I've configured Twig to autoescape all my variables.

twig:
    autoescape:   true

But this doesn't filter anything. Both HTML and JavaScript aren't escaped. There is no custom autoescape_service and I'm not filtering the variables with |raw or { autoescape false }.

I've double check the generated config to make sure the value hasn't been overwritten. In app/cache/dev/appDevDebugProjectContainer.xml under the twig service definition the arguments are as follows:

<argument key="debug">true</argument>
<argument key="strict_variables">false</argument>
<argument key="cache">false</argument>
<argument key="autoescape">true</argument>
<argument key="exception_controller">twig.controller.exception:showAction</argument>
<argument key="autoescape_service">null</argument>
<argument key="autoescape_service_method">null</argument>
<argument key="charset">UTF-8</argument>

Is there another way that Twig overwrites the autoescape option that I'm missing? Or how can I force enable it?

like image 659
Waaghals Avatar asked Dec 04 '25 19:12

Waaghals


1 Answers

I always find the problem after asking my questions after wasting hours trying to find a solution.

During development twig.autoescape was set to false. Later XSS protection was needed. And and {{ autoescape }} block was added to some of the fields. Some time later a |raw filter has been added in the autoescape block to disable autoescaping on some fields again.

I missed the |raw filters in the unnecessary autoescape blocks. (I must have skipped the content thinking autoescape was set to true, but the |raw filter gets applied later so the content stays raw.

like image 160
Waaghals Avatar answered Dec 07 '25 14:12

Waaghals



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!