Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i format decimal to currency format in mustache?

I'm using mustache to render json data received through Ajax.

I want to render this number in currency format:

{{price}}

e.g.: 12300

How can I render it as:

"12,300"

using mustache templating engine ?

like image 836
brainydexter Avatar asked Jul 18 '12 07:07

brainydexter


2 Answers

Mustache is very minimalistic and doesn't provide any support for this.

You either have to supply the formatted data or a function returning the formatted data

{ priceDecimal: function () { return formatDecimal(this.price); } }

Another alternative is to use handlebars.js which supports helper functions

Handlebars.registerHelper('decimal', function(number) {
  return formatDecimal(number);
});

and use it like this

{{decimal price}}
like image 155
Otto Allmendinger Avatar answered Sep 18 '22 22:09

Otto Allmendinger


While I agree with Lucero's answer, it is possible to use a function in Mustache to format your data.

Simple template:

<ul>
    {{#price}}
        <li>{{commaFormat}}</li>
    {{/price}}
</ul>

JavaScript to process the data with a formatting function for your prices:

var tpl = $('#tpl').html(),
    data = {
        price: ['1234', '123', '123456', '1234567890'],
        commaFormat: function() {
            // adapted from https://stackoverflow.com/questions/2901102/how-to-print-number-with-commas-as-thousands-separators-in-javascript
            return this.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        }
    },
    html = Mustache.to_html(tpl, data);

document.write(html);​

Resulting HTML:

<ul>
    <li>1,234</li>
    <li>123</li>
    <li>123,456</li>
    <li>1,234,567,890</li>
</ul>

Here's the working jsFiddle to inspect and play with further.

like image 22
maxbeatty Avatar answered Sep 18 '22 22:09

maxbeatty