Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpret html string using handlebars but escape script tags

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.

like image 367
Savanaly Avatar asked Jan 31 '14 00:01

Savanaly


People also ask

What is the difference between HBS and HTML?

HTML is the language that browsers understand for laying out content on a web page. . hbs stands for Handlebars, the name of a tool that lets you write more than just HTML. When you start an app with ember serve , your templates are compiled down to something that Ember's rendering engine can process more easily.

How do you comment on handlebars?

Template comments If you'd like the comments to show up just use HTML comments, and they will be output. Any comments that must contain }} or other handlebars tokens should use the {{!-- --}} syntax.

How do you pass an array in handlebars?

You can almost accomplish this with the use of eval() , using a helper like this: Handlebars. registerHelper('printArray', function(values) { var array = eval(values); if (array. constructor === Array()) { ... } }


1 Answers

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.

like image 198
Jason Avatar answered Oct 22 '22 21:10

Jason