简体   繁体   中英

twig escape('js') symfony2

Let's say I have article with content (content has html tags).. so:

{{article.content|raw}}

and it looks good.

Problem is if user adds script tags - So I try doing

{{article.content|raw|e('js')}}

and it escapes all.. I mean html and so on..

I get double escaped text, I don't have any html tags any more, they all are escaped.. is it some kind of twig bug or what?

example: I have "<p>test</p>"

with {{article.content|raw}} I will see "test" with {{article.content|raw|e('js')}} I will see "\\x3Cp\\x3Etestas\\x3C\\x2Fp\\" . So what's wrong? I know I can escape script tags on server side, but I am so interested in knowing what's wrong with my approach..

You have the wrong tool for the job using the escape filter. With what you have written, the "raw" filter does nothing and the escape escapes the string you are outputting so that it will be suitable for inclusion as data inside a Javascript section of your output.

What you are looking for is an XSS filter like HtmlPurifier . Once you have used composer or direct installation to include an XSS filter in your project, you can then write a custom filter for Twig that will filter out XSS vectors like script tags etc. and leave you with a variable safe to output via the raw filter.

Tested in https://twigfiddle.com/

{{'<p>test</p><script>const me = "hi"</script>'|raw}}
{{'<p>test</p><script>const me = "hi"</script>'|e('js')}}
{{'<p>test</p><script>const me = "hi"</script>'|e('html')}}
{{'<p>test</p><script>const me = "hi"</script>'|e('html_attr')}}
{{'<p>test</p><script>const me = "hi"</script>'|striptags}}
{{'<p>test</p><script>const me = "hi"</script>'|striptags|raw}}

/*
<p>test</p><script>const me = "hi"</script>
\u003Cp\u003Etest\u003C\/p\u003E\u003Cscript\u003Econst\u0020me\u0020\u003D\u0020\u0022hi\u0022\u003C\/script\u003E
&lt;p&gt;test&lt;/p&gt;&lt;script&gt;const me = &quot;hi&quot;&lt;/script&gt;
&lt;p&gt;test&lt;&#x2F;p&gt;&lt;script&gt;const&#x20;me&#x20;&#x3D;&#x20;&quot;hi&quot;&lt;&#x2F;script&gt;
testconst me = &quot;hi&quot;
testconst me = "hi"
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM