symfony2 twig whitelist html tags

后端 未结 5 2441
盖世英雄少女心
盖世英雄少女心 2021-02-20 08:23

I pass a variable to my twig template in Symfony2, this variable may contain
html tags, I have tried to create an extension (function), but the variabl

相关标签:
5条回答
  • 2021-02-20 08:45

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

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

    Unfortunately it's not the case. Only available strategies are html and js. They're hard coded in the twig_escape_filter() function defined in a Twig_Extension_Core class file.

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

    {{ var|raw|customescape }}
    

    Here's an example of custom twig extension and how to register it in Symfony: Symfony2 Twig extension

    0 讨论(0)
  • 2021-02-20 08:48
    {{ var|nl2br }}
    

    and/or

    {{ var|raw|nl2br }}
    

    nl2br reference

    0 讨论(0)
  • 2021-02-20 08:50
    {{ var|striptags('<br>')|raw }} 
    

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

    both

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

    and

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

    throw an "Array to string conversion" exception during the rendering of a template.

    Be also carefull that strip_tags php function doesn't escape html attribute like "onclick".

    0 讨论(0)
  • 2021-02-20 08:56

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

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

    you can allow multiple tags with following code:

    {{ var|striptags('<br><p>')|raw }}
    
    0 讨论(0)
  • 2021-02-20 09:04

    You can do like that :

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

    For instance,

    <br>
    

    won't escape

    <br> and <br />
    

    and

    <p>
    

    won't escape

    <p> and </p>
    

    etc.

    0 讨论(0)
提交回复
热议问题