Handlebars function to format currency with javascript

23,378

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/

Share:
23,378
jahrichie
Author by

jahrichie

full stack developer. love everything.

Updated on January 24, 2020

Comments

  • jahrichie
    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
    Tai about 9 years
    Thanks for the above but it doesnt handle for $24000.50 for example as a bid. Any advice on that part?
  • mu is too short
    mu is too short about 9 years
    @TaiHirabayashi You mean the .50 part? Probably best to look for a prinft JavaScript library and wrap that in a Handlebars helper.
  • Alan Mabry
    Alan Mabry almost 8 years
    Trailing zeros won't be stripped with this syntax: ${{{price}}}