Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop nunjucks from escaping HTML

Tags:

I have a comments AJAX call which returns data of the posted comment, I also have @mention functionality built in, the server side is processing the @mentions and doing a str_replace on the mentioned users replacing their names with an a tag within the response, for example:

{    data: {       comment: "<a href=\"profile/derp\">Username</a> hey what's up"    } } 

However I can't seem to find in the documentation how to allow nunjucks to print this as actual HTML, it escapes it and displays the code instead of letting it be a real a tag.

Does anyone know how I can allow this to be printed as an actual a tag?

like image 666
André Figueira Avatar asked Apr 25 '15 13:04

André Figueira


People also ask

How do you define a variable in Nunjucks?

A variable looks up a value from the template context. This documents details on the variables available in JMWE and how to create custom variables. If you want to insert the value of a variable in your template, you can use the following syntax: {{ myVar }} .

How do I comment in Njk?

Comments. You can write comments using {# and #} . Comments are completely stripped out when rendering.


2 Answers

OK so almost immediately after I posted this I found the answer! for anyone else looking it's simply this; within your template where you're printing your variable add the safe filter, which will disable automatic escaping.

{{ comment.content|safe }} 

Although this means it's vulnerable to XSS injection, so make sure you add your protection on the server side.

like image 165
André Figueira Avatar answered Nov 17 '22 08:11

André Figueira


You can also avoid escaping globally using:

nunjucks.configure({ autoescape: false }); 
like image 44
jibe Avatar answered Nov 17 '22 07:11

jibe