Javascript 如何使用 Handlebars 解码 HTML 实体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10654234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to decode HTML entity with Handlebars
提问by Maverick
I'm using the Handlebars templating engine on the app I'm building to render the data I get from the server.
我正在构建的应用程序上使用 Handlebars 模板引擎来呈现我从服务器获取的数据。
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.
我知道默认情况下它会转义 HTML 值,并且您必须使用三方括号{{{text}}}
才能text: <p>Example</p>
将其呈现为 HTML 元素。
The problem is, what do I do if the data I receive, including the HTML tags, is already escaped?
问题是,如果我收到的数据(包括 HTML 标签)已经转义了,我该怎么办?
So, if I receive data like:
所以,如果我收到如下数据:
text: <p>Example</p>
How do I force handlebars to translate it and render it as normal HTML?
如何强制把手翻译它并将其呈现为普通 HTML?
回答by Jér?me Mahuet
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:
您必须先对其进行解码,然后将其传递给带有三重括号的车把。我知道一个使用 jQuery 解码 html 实体的小技巧:
// encoded is "<p>Example</p>" in your example
var decoded = $('<textarea />').html(encoded).val();
// decoded should now return <p>Example</p>
回答by Vishnu Prasanth G
Handlebars provides helpers and write a custom helper like follows under Handlebars_helpers.js
Handlebars 提供了帮助器,并在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
并在您的.handlebar
文件或.hbs
文件中使用此助手,如下所示
{{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.
没有 Jquery 的帮助,您可以在车把内的任何地方使用它。即使您可以使用助手单独传递数据,这将返回带有前置和附加标签的数据。