Lorenzo B
Lorenzo B

Reputation: 33428

Handlebars helper does not work correctly

I have created an Handlebars helper like the following.

Handlebars.registerHelper("format_currency", function(value, currency){

    var symbol = "";
    if(currency === "EUR") symbol = "€";
    else if ... // other code here

    return value + " " + symbol;
});

that I use in the following manner

{{format_currency amount currency}}

When I run the application application, the value field has the correct value (say 1.5) while the currency in an object that hash an hash property inside. Why? Here I would expect the currency I passed in (say "EUR").

Am I missing something? Thanks.

Upvotes: 2

Views: 3615

Answers (1)

mu is too short
mu is too short

Reputation: 434585

I don't know what "an object that hash an hash property inside" means but I see one problem with your helper (or the way you're using it) that will make it produce odd results.

When you use {{...}}, Handlebars is expecting plain text so it will HTML encode it. So if your symbol ends up being "€", the ampersand will be HTML encoded and you'll get € added to your template rather than the Unicode entity for the Euro symbol.

There are a few ways around this problem.

Triple Stashes

One way to fix the encoding problem use triple-stashes in your template to disable the HTML encoding:

{{{format_currency amount currency}}}

Demo: http://jsfiddle.net/ambiguous/Q4FcR/

Plain Unicode

Another way is to abandon the entities in favor of a raw Unicode Euro character:

if(currency === "EUR")
    symbol = '€';

Then you don't have to worry about double-stashes or triple-stashes or HTML encoding or ...

Demo: http://jsfiddle.net/ambiguous/Mfuk7/

SafeString

Another way is to return a Handlebars.SafeString instead of a String:

Handlebars will not escape a Handlebars.SafeString. If you write a helper that generates its own HTML, you will usually want to return a new Handlebars.SafeString(result).

So you'd have this in your helper:

return new Handlebars.SafeString(value + " " + symbol);

Demo: http://jsfiddle.net/ambiguous/AZtCE/

Upvotes: 8

Related Questions