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 ?
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}}
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.
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