Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode HTML entity with Handlebars

Tags:

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?

like image 521
Maverick Avatar asked May 18 '12 14:05

Maverick


People also ask

Does handlebars escape HTML?

HTML EscapingHandlebars will not escape a Handlebars. SafeString . If you write a helper that generates its own HTML, you will usually want to return a new Handlebars.

How do I decrypt HTML code?

Wikipedia has a good expalanation of character encodings and how some characters should be represented in HTML. Load the HTML data to decode from a file, then press the 'Decode' button: Browse: Alternatively, type or paste in the text you want to HTML–decode, then press the 'Decode' button.

What is HTML entity decode?

HTML encoding converts characters that are not allowed in HTML into character-entity equivalents; HTML decoding reverses the encoding. For example, when embedded in a block of text, the characters < and > are encoded as &lt; and &gt; for HTTP transmission.


2 Answers

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> 
like image 136
Jérôme Mahuet Avatar answered Sep 19 '22 07:09

Jérôme Mahuet


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.

like image 38
Vishnu Prasanth G Avatar answered Sep 18 '22 07:09

Vishnu Prasanth G