Stop nunjucks from escaping HTML

I have an AJAX comment that returns the data of a published comment, I also have @mention built-in functionality, the server side processes @mentions and does str_replace for the mentioned users, replacing their names with a tag inside the response, for example:

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

However, I cannot find in the documentation how to allow nunjucks to print this as real HTML, it avoids it and displays the code instead of turning it into a real tag.

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

+9
source share
3 answers

Well, so almost immediately after I posted this, I found the answer! for everyone who is looking for it just like that; in the template where you print the variable, add a safe filter that will disable auto-escaping.

 {{ comment.content|safe }} 

Although this means that it is vulnerable to the implementation of XSS , so make sure that you add server-side protection.

+40
source

You can also avoid a global exit by using:

 nunjucks.configure({ autoescape: false }); 
+8
source

You can pass comment metadata and let the template create HTML:

 <p> <a href="{{ comment.user.url }}">{{ comment.user.name }}</a> {{ comment.text }} </p> 

Then pass the following metadata:

 comment: { user: { url: "profile/derp", name: "Username" }, text: "hey what up" } 
+4
source

Source: https://habr.com/ru/post/985944/


All Articles