66

I am using Mustache to render templates.

I have this json object:

  {
    title: "Foo bar", 
    content: "<p> Html here </p>", 
    footer: "footer content here"
  }

I have a Mustache template like:

  <div id="box">
    <div id="title"> {{title}} </div> 
    <div id="content"> {{content}} </div> 
    <div id="footer"> {{footer}} </div> 
  </div>

My problem is that the html within the variable content is not getting rendered but instead is just getting printed to the screen.

I see (in non-view source window): <p> Html here </p>, where I would only want to see that if I viewed the page source.

How can I fix such that when I pass in a string to a mustache template the HTML inside gets rendered? I am calling mustache.render(templates.all,data); as my call to mustache.

Snow_Mac
  • 5,169
  • 16
  • 50
  • 79

1 Answers1

153

From the Mustache documentation:

All variables are HTML escaped by default. If you want to return unescaped HTML, use the triple mustache: {{{name}}}.

So you just have to use eg.{{{content}}} in your template:

  <div id="box">
    <div id="title"> {{title}} </div> 
    <div id="content"> {{{content}}} </div> 
    <div id="footer"> {{footer}} </div> 
  </div>
Amy
  • 7,250
  • 2
  • 17
  • 31
  • 1
    I know that this is an old post, but I need to solve this but with the difference that I want to assign {{{content}}} to a javascript variable in order to use in oder javascript files inside of my site. – cmarrero01 Feb 17 '17 at 23:59
  • If you want to get the `content` as a variable, you would do that in the code that is calling the template render. You can't extract the data out of a rendered template. (A hack-ish way, would be to render the template, then extract it out of the DOM using `documents.querySelector(...).textContent`) – Amy Mar 09 '17 at 08:27
  • 1
    @cmarrero01 then you can put a partial {{> cnt}} to template and pass variable object `{"cnt": content}` as third parameter to `render` function. Like here http://jsfiddle.net/EYDfP/169/ – Dima Fomin Mar 13 '17 at 17:03
  • The perfect solution as what I wanted for. +1 – Chandresh M May 26 '20 at 06:41