Handlebars.SafeString vs. Spacebars.SafeString


#1

What is the difference between Handlebars.SafeString() and Spacebars.SafeString()?


#2

Nothing. Handlebars.SafeString() is a deprecated alias for Spacebars.SafeString().


#3

Nothing, they both return a highly unsafe string.

For those who naively believe these functions turn an unsafe string into a safe one, always remember they do the exact opposite: they turn a safe string (i.e. a string that will be escaped by Blaze) into an unsafe one (i.e. a string that won’t be checked before display, allowing malicious code injection).


#4

Ok good to know.

So how do I do it right, when returning html in a template helper?
How do I do it safely?

  preview: function() {
    var text = Session.get('summernoteEditor');
    return new Handlebars.SafeString(text);
  }

#5

You need to sanitize your html before displaying it (ideally immediately before). Maybe Summernote has a function for this, or you can have a look at those packages.

Then, for actually displaying the string with Blaze, I use {{{...}}} (more self-documented) rather than Spacebars.SafeString() (too misleading).


#6

I have the html in my mongo database.
Is it then save to display the html using Blaze {{{...}}}?


#7

But where does it come from?


#8

It is inserted over a special page that is only accessible by admins (trusted users).
So inserting it into the db should be no issue.
It’s just a question of displaying it.
(sorry, my code is a bit misleading :slight_smile: )


#9

Yes, if the HTML is just inserted to the db by trusted admins and there’s no other possible way for suspect html to get into the db, then it’s safe just display it using the triple braces syntax:

In a template file:

<template name="myTemplate">
  {{#with document}}
    {{{html}}}
  {{/with}}
</template>

In the template helper file:

Template.myTemplate.helpers({
  document: function () {
    return myDocuments.findOne();
  }
});

where a document from myDocuments looks like:

{
  _id: "asdga315gq4564",
  html: "This is <strong>html</strong>!"
}