Interpret html string using handlebars but escape script tags

南笙酒味 提交于 2019-12-10 13:12:22

问题


I'm bringing in a string of html for my page and I consider it html-safe except for script tags. I'm aware that triple braces will escape the html, what are the steps to leave out any script tags?

Example

var foo = "<h1>Foo</h1><script>some script that might possibly be in here</script><p>bar</p>

then in my .hbs:

{{{foo}}}

I would like to see the h1 and the paragraph but have scripts left out.

Thanks in advance.


回答1:


You have a couple of options:

  1. Remove the script tags before passing it as context into your Handlebars template.

  2. Create a Handlebars helper to use in place of the triple curly braced expression. Something like this:

    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);
    });

Then use it in your template like this:

    {{strip-scripts foo}}

You don't need to use triple curly braces when using the helper, because your helper returns a SafeString already.

The helper may be more beneficial than the first option, because you can reuse it throughout your templates.

Check out this StackOverflow question for help on how to strip the script tags out safely: Removing all script tags from html with JS Regular Expression

If you're doing this server-side with Node.js, you can use something like Cheerio instead of jQuery.



来源:https://stackoverflow.com/questions/21470267/interpret-html-string-using-handlebars-but-escape-script-tags

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