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

Answers


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

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

Need Your Help

ASP .NET MVC Disable Client Side Validation at Per-Field Level

c# jquery asp.net-mvc validation jquery-validate

I'm using ASP .NET MVC 3 with Data Annotations and the jQuery validate plugin.

Debugging Stored Procedure in SQL Server 2008

sql-server sql-server-2008 debugging

Is there any way to debug a stored procedure on SQL Server 2008?