Handlebars helper - returning HTML not text

I wrote a simple helper for my template. Here's the code:

Handlebars.registerHelper('splitQuote', function (string) { if (string.indexOf('|') !== -1) { return string.replace('|', '<span>') + '</span>'; } return string;
});

So I pass a string, and split the string by '|' character. I also want to put second part into span tags.

Problem is, the result that is being returned is pure text, so I get span tags like a text, not HTML.

Does anyone know what's the catch?

Tnx

2 Answers

You don´t need to use SafeString. Instead, use the "triple moustaches" from handlebar:

From Handlebars web site, HTML Escaping section:

Handlebars HTML-escapes values returned by a {{expression}}. If you don't want Handlebars to escape a value, use the "triple-stash", {{{.

So, a simple triple quote in your html will avoid escaping:

{{{splitQuote}}} 
1

You have to mark the string as html in your helper if you want to Handlebars not to escape it. Use Handlebars.safeString to do this. The below should suit your needs

Handlebars.registerHelper('splitQuote', function(string) { if (string.indexOf('|') !== -1) { return new Handlebars.SafeString(string.replace('|', '<span>') + '</span>'); } return string;
});

As mentioned in comments you should probably escape the passed string using Handlebars.Utils.escapeExpression(string) to encode the string before you do your custom formatting. I'd recommend writing like this:

Handlebars.registerHelper('splitQuote', function(string) { string = Handlebars.Utils.escapeExpression(string); if (string.indexOf('|') !== -1) { string = string.replace('|', '<span>') + '</span>'; } return new Handlebars.SafeString(string); // mark as already escaped
});
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like