Question

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

Was it helpful?

Solution 2

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

OTHER TIPS

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}}} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top