문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top