Search code examples
javascriptlodashunderscore.js-templatinghtml-escape-characters

Lodash _.template rendering escaped characters


I have some data comming already escaped from a "controller":

<b>

And I'm using lodash template (_.template), when rendered, it still in plain text:

<b>

Expected:

<b>

How can I render this kind of html part without browser consider it's like a plain text and not a element?


Solution

  • Call a function to unescape your escaped HTML. Depending on your case, you may choose to unescape your data and pass the result to the template or, as in this snippet, write the function call in the template:

    var temp = _.template("<%= htmlDecode(name) %>");
    
    function htmlDecode(input) {
      var doc = new DOMParser().parseFromString(input, "text/html");
      return doc.documentElement.textContent;
    }
    
    console.log(temp({ name: "&lt;em&gt;Test&lt;/em&gt;" }));
    

    http://jsbin.com/laretumiqa/edit?html,js,console,output

    (the htmlDecode function comes from this question: Unescape HTML entities in Javascript?)