Handlebars function to format currency with javascript
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/
![jahrichie](https://i.stack.imgur.com/nFGD8.png?s=256&g=1)
Comments
-
jahrichie over 4 years
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}}
-
Tai about 9 yearsThanks for the above but it doesnt handle for $24000.50 for example as a bid. Any advice on that part?
-
mu is too short about 9 years@TaiHirabayashi You mean the
.50
part? Probably best to look for aprinft
JavaScript library and wrap that in a Handlebars helper. -
Alan Mabry almost 8 yearsTrailing zeros won't be stripped with this syntax: ${{{price}}}