twig.js icon indicating copy to clipboard operation
twig.js copied to clipboard

nl2br without escaping

Open nine-2-five opened this issue 7 years ago • 5 comments

I'd like to create <br> from \n and output these tags(remove others): '<b>,</b>,<a>,</a>,<pre>,</pre>,<br>,<br/>,<p>,</p>'

Is it possible?

nine-2-five avatar Jan 05 '18 11:01 nine-2-five

Have you found something that works in PHP Twig but not in Twig.js, or are you wondering how to turn

\n<b>,</b>,<a>,</a>,<pre>,</pre>,<br>,<br/>,<p>,</p>,<em>

into

<br/><b>,</b>,<a>,</a>,<pre>,</pre>,<br>,<br/>,<p>,</p>,

?

olets avatar Jan 05 '18 15:01 olets

It's been some time since the last time I used php twig. I'm in a bit of flu situation right now, I can't seem to combine/order the filters to get those html tags to output, the best I can come up is to display those html tags but they're all escaped. {{- content|raw|nl2br|striptags('<b>,</b>,<a>,</a>,<pre>,</pre>,<br>,<br/>,<p>,</p>') -}}

nine-2-five avatar Jan 05 '18 15:01 nine-2-five

Did a test and I understand your problem now. nl2br unavoidably escapes everything.

{{ '\n&<a>'|nl2br }}

should compile to

<br />
&<a>

but it compiles to

<br />
&amp;&lt;a&gt;

This is because of the escape in https://github.com/twigjs/twig.js/blob/master/src/twig.filters.js#L442

Simply removing the escape breaks the test for when autoescape is on. Someone more familiar with autoescape should take it from here

olets avatar Jan 05 '18 19:01 olets

In TwigPHP, nl2br filter is considered safe if the escaping strategy is "html" - the default:

https://github.com/twigphp/Twig/blob/45990c3644032f255824a6a3819ba5d828236eef/lib/Twig/Extension/Core.php#L159

Removing the escape should fix the issue. It's breaking the test because nl2br test is wrong:

it("should not escape br tags if autoescape is on", function() {
            twig({
                autoescape: true,
                data: '{{ test|nl2br }}'
            }).render({
                test: '<test>Line 1\nLine2</test>'
            }).should.equal("&lt;test&gt;Line 1<br />\nLine2&lt;/test&gt;");
});

TwigPHP compile the test to:

<test>Line 1<br />
Line2</test>

ericmorand avatar Feb 07 '18 23:02 ericmorand

Here it is working in TwigPHP and not working in twig.js.

willrowe avatar Jul 26 '22 15:07 willrowe