Nunjucks nl2br does not exist?

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

Does anyone know how to solve it using an equivalent filter or another solution? Or do I need to create a filter?

+7
javascript nl2br nunjucks
source share
2 answers

Nunjucks has built-in shielding. If you set {autoescape: true} when configuring Nunjucks, you don’t need to do anything. Otherwise, you can use the escape filter.

If you just want to change the newlines, do the following:

 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.

+3
source share

Now in nl2br filter (see the documentation )

So, I have insecure text, but you still want newlines to be replaced with tags <br/> , you can use the following example for documents

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

which will output

 foo<br />\nbar 

and will be displayed as

Foo
bar

0
source share

All Articles