Sav*_*aly 6 mustache handlebars.js
我为我的页面引入了一串html,除了脚本标签,我认为它是html安全的.我知道三重括号会逃脱html,省略任何脚本标签的步骤是什么?
例
var foo = "<h1>Foo</h1><script>some script that might possibly be in here</script><p>bar</p>
Run Code Online (Sandbox Code Playgroud)
然后在我的.hbs中:
{{{foo}}}
Run Code Online (Sandbox Code Playgroud)
我想看看h1和段落,但是遗漏了脚本.
提前致谢.
你有几个选择:
在将脚本标记作为上下文传递到Handlebars模板之前删除它们.
创建一个Handlebars帮助器来代替三重花括号表达式.像这样的东西:
Handlebars.registerHelper('strip-scripts', function(context) {
var html = context;
// context variable is the HTML you will pass into the helper
// Strip the script tags from the html, and return it as a Handlebars.SafeString
return new Handlebars.SafeString(html);
});
Run Code Online (Sandbox Code Playgroud)
然后在你的模板中使用它,如下所示:
{{strip-scripts foo}}
Run Code Online (Sandbox Code Playgroud)
使用帮助程序时不需要使用三重花括号,因为助手已经返回一个SafeString.
帮助程序可能比第一个选项更有用,因为您可以在整个模板中重复使用它.
查看此StackOverflow问题以获取有关如何安全地删除脚本标记的帮助:使用JS Regular Expression从html中删除所有脚本标记
如果您使用Node.js在服务器端执行此操作,则可以使用Cheerio而不是jQuery.
| 归档时间: |
|
| 查看次数: |
7463 次 |
| 最近记录: |