Symfony2 twit whitelist html symbol tags

I pass the variable to my twig template in Symfony2, this variable may contain <br /> html tags, I tried to create an extension (function), but the variable is still reset.

How can I output the twig variable that allows the <br /> tag? Is there a simple solution to just allow whitelisting of valid tags in specific templates?

I searched about sandboxes, but I'm not sure if this is my solution.

edit: I still want the variable to be escaped, but only allow the <br /> tag.

+8
html escaping templates symfony twig
source share
5 answers

Initially, I thought it should be possible to write custom escaper strategies so that you can do something like this:

 {{ var|escape('html-custom') }} 

Unfortunately, this is not so. Only html and js strategies are available. They are hardcoded in the twig_escape_filter() function defined in the Twig_Extension_Core class Twig_Extension_Core .

It seems your only option is to write a custom setting with a new filter:

 {{ var|raw|customescape }} 

Here is an example of a custom twig extension and how to register it with Symfony: Symfony2 Twig extension

0
source share

Actually, you can use the PHP strip_tags native function by doing the following:

 {{ var|striptags('<br>')|raw }} 

You can allow multiple tags with the following code:

 {{ var|striptags('<br><p>')|raw }} 
+34
source share

You can do this:

 {{ text | striptags('<p><b><br') | raw }} 

For example,

 <br> 

will not work

 <br> and <br /> 

and

 <p> 

will not work

 <p> and </p> 

and etc.

+3
source share
 {{ var|striptags('<br>')|raw }} 

works fine, but I don't know how to pass an array to the php strip_tags function using this branch filter.

and

 {{ var|striptags(['<br>', '<b>'])|raw }} 

and

 {% set allow = ['<br>', '<b>'] %} {{ var|striptags(allow)|raw }} 

throw an exception "Array to string conversion" when rendering the template.

Also, be careful that the str_tags php function does not remove the html attribute, such as "onclick".

+1
source share
 {{ var|nl2br }} 

and / or

 {{ var|raw|nl2br }} 

link nl2br

0
source share

All Articles