I have this in my handlebar template:
<span class="currencyFormatMe">{{_current_price}}</span>
An example of what the loop returns|: Bid: $24000
I'd like to format that with commas and i'm failing.
I have this function which works in the console, but fails when adapted to the codebase with handlebars.
$.fn.digits = function(){
return this.each(function(){
$(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
})
}
And I call it like $("span.currencyFormatMe").digits();
Again it all works in the console, but fails when adapted. Any pointers are very welcome
Tried it with a registerhelper:
Handlebars.registerHelper('formatCurrency',
$.fn.digits = function(){
return this.each(function(){
$(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
})
}
);
Calling:
{{formatCurrency _current_price}}
Handlebars doesn't allow you to write JavaScript directly within templates. Instead, it gives you helpers. These are JavaScript functions that you can call from your templates, and help you reuse code and create complex templates. To call a helper, just use it as an expression - {{helpername}} .
The Handlebars. js is a Javascript library used to create reusable webpage templates. The templates are combination of HTML, text, and expressions. The expressions are included in the html document and surrounded by double curly braces. These expressions are placeholders for content to be inserted by our Handlebars.
Handlebars expressions are the basic unit of a Handlebars template. You can use them alone in a {{mustache}} , pass them to a Handlebars helper, or use them as values in hash arguments.
You have a couple simple options here.
You can stick with your jQuery plugin and apply it after the Handlebars template has been filled in; something like this:
<script id="t" type="text/x-handlebars">
<span class="currencyFormatMe">{{_current_price}}</span>
</script>
and then:
$.fn.digits = function(){
return this.each(function(){
$(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
})
};
var t = Handlebars.compile($('#t').html());
var h = t({
_current_price: 1000
});
$('<div>').append(h).find('.currencyFormatMe').digits();
Demo: http://jsfiddle.net/ambiguous/732uN/
Or you can convert your plugin into a Handlebars helper and do the formatting in the template. If you want to do this you just have to format the value passed to the helper rather than messing around with $(this)
inside the helper. For example:
<script id="t" type="text/x-handlebars">
{{formatCurrency _current_price}}
</script>
and then:
Handlebars.registerHelper('formatCurrency', function(value) {
return value.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
});
var t = Handlebars.compile($('#t').html());
var h = t({
_current_price: 1000
});
Demo: http://jsfiddle.net/ambiguous/5b6vh/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With