Nunjucks nl2br does not exist?
Asked Answered
S

2

12

I need a filter like the Jinja "nl2br", but in the Nunjucks. In the documentation are a mention (https://mozilla.github.io/nunjucks/templating.html), but I searched it in the nunjucks code (https://github.com/mozilla/nunjucks/blob/master/src/filters.js) and it does not exist.

Somebody knows how to solve it with a equivalent filter or another solution? Or I need to create the filter?

Steamtight answered 5/2, 2016 at 16:43 Comment(0)
P
6

Nunjucks has built-in escaping. If you set {autoescape: true} when settings up Nunjucks, then you don't need to do anything. Otherwise, you can use the escape filter.

If you just want to escape newlines, then do this:

env.addFilter('nl2br', function(str) {
    return str.replace(/\r|\n|\r\n/g, '<br />')
})

and use the newly created nl2br filter.

Note: env is your Nunjucks environment.

Petropavlovsk answered 7/2, 2016 at 23:5 Comment(2)
I had already setted the autoscape like true, but not works. Only the escape filter doesn't work too. My solution was to create the filter and use it with the safe like it: {{description|nl2br|safe}}Steamtight
@RenathoDeCarliRosa that's a bad idea, because it will allow any html/script to be intjected into the htmlUrbani
M
5

There is now a nl2br filter in nunjucks (see the documentation)

So i've yout got some unsafe text, but you still want to have new lines changed to <br/> tags, you can use the following example for the docs

{{ "foo\nbar" | striptags(true) | escape | nl2br }}

which will output

foo<br />\nbar

and be displayed as

foo
bar

Murk answered 3/7, 2019 at 10:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.