25

I'm using the Handlebars templating engine on the app I'm building to render the data I get from the server.

I know that it escapes HTML values by default and that you have to use the triple brackets {{{text}}} in order for text: <p>Example</p> to be rendered as an HTML element.

The problem is, what do I do if the data I receive, including the HTML tags, is already escaped?

So, if I receive data like:

text: &lt;p&gt;Example&lt;/p&gt;

How do I force handlebars to translate it and render it as normal HTML?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Maverick
  • 1,988
  • 5
  • 24
  • 31
  • 2
    Most template languages assume the data is either encoded for the target output or is plain text that needs encoding. They don't come with "decode from arbitary encode" features. – Quentin May 18 '12 at 14:21

2 Answers2

41

You have to decode it first, then pass it to handlebars with triple brackets. I know a small tip to decode html entities with jQuery:

// encoded is "&lt;p&gt;Example&lt;/p&gt" in your example
var decoded = $('<textarea />').html(encoded).val();
// decoded should now return <p>Example</p>
Jérôme Mahuet
  • 874
  • 8
  • 13
  • 2
    +1 for using this nice hack to decode without the need of `.replace(/>/g, '>').replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/ – GodLesZ May 18 '12 at 14:22
  • I don't mind voting up twice for this answer if I can. – Tuyen Nguyen Mar 13 '14 at 16:19
  • 4
    While the answer is correct, It's better to not use the jQuery hack for decoding html entities. See http://stackoverflow.com/a/11715395/1259882 for more details. – david.binda Mar 12 '15 at 10:53
10

Handlebars provides helpers and write a custom helper like follows under Handlebars_helpers.js

Handlebars.registerHelper('encodeMyString',function(inputData){
    return new Handlebars.SafeString(inputData);
});

and use this helper in your .handlebar files or .hbs files as follows

{{encodeMyString myHTMLData}}

Without help of Jquery you can use it any where inside your handlebars. Even you can use the helper to pass the data alone and which will return the data with prepended and appended tags.

Nik Sumeiko
  • 8,263
  • 8
  • 50
  • 53
Vishnu Prasanth G
  • 1,133
  • 12
  • 12