How to decode HTML entity with Handlebars

喜夏-厌秋 提交于 2019-12-03 05:46:13

问题


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?


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/10654234/how-to-decode-html-entity-with-handlebars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!