twig.js
twig.js copied to clipboard
nl2br without escaping
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?
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>,
?
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>') -}}
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 />
&<a>
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
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("<test>Line 1<br />\nLine2</test>");
});
TwigPHP compile the test to:
<test>Line 1<br />
Line2</test>
Here it is working in TwigPHP and not working in twig.js.