Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 : Auto htmlentities using Twig

I'm displaying some variable retrieved in my database using Twig :

<p>{{ my_variable }}</p>

The thing is this variable may contain html tags, such as "<br />".

Twig seems to automatically call some htmlentities-like function when displaying variables.

Is there any way to disable it so that when I display a variable containing "Hello<br />world !" I get :

Hello 
world !

rather than :

Hello<br />world !

Thanks

like image 358
Yoot Avatar asked Jan 15 '13 15:01

Yoot


People also ask

What is raw in twig?

raw. By default, everything in Twig gets escaped when automatic escaping is enabled. If you don't want to escape a variable you'll have to explicitly mark it as safe which you can do by using the raw filter. This only works if the raw filter is the last filter that is applied to the filter.

What is block in twig?

Blocks are used for inheritance and act as placeholders and replacements at the same time. They are documented in detail in the documentation for the extends tag. Block names must consist of alphanumeric characters, and underscores. The first char can't be a digit and dashes are not permitted.


2 Answers

Use {{ my_variable|raw }} to prevent my_variable from being automatically escaped.

See Twig documentation: http://twig.sensiolabs.org/doc/filters/raw.html

like image 131
dbrumann Avatar answered Oct 16 '22 11:10

dbrumann


Try using this

{% autoescape false %}{{ my_variable}}{% endautoescape %}
like image 2
Mirage Avatar answered Oct 16 '22 10:10

Mirage