26

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?

Malekai
  • 4,765
  • 5
  • 25
  • 60
André Figueira
  • 6,048
  • 14
  • 48
  • 62

3 Answers3

78

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.

Malekai
  • 4,765
  • 5
  • 25
  • 60
André Figueira
  • 6,048
  • 14
  • 48
  • 62
12

You can also avoid escaping globally using:

nunjucks.configure({ autoescape: false });
Malekai
  • 4,765
  • 5
  • 25
  • 60
jibe
  • 578
  • 1
  • 4
  • 12
5

You could consider passing the comment's meta data and letting the template create the HTML:

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

Then pass the following meta data:

comment: {
  user: { url: "profile/derp", name: "Username" },
  text: "hey what's up"
}
Malekai
  • 4,765
  • 5
  • 25
  • 60
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • Thanks for your suggestion, but the issue is the template does not know before hand if there will be a link, as this link is only added if there are mentions, which can be within a comment for example. – André Figueira May 28 '15 at 14:01
  • 1
    @AndréFigueira you can add a conditional statement. – Ja͢ck May 28 '15 at 14:11