Handlebar helper and .toLocaleString

I display results of a json in Handlebars including numbers that I'd like to format with .toLocaleString(). My json sample:

[{"id": "1",
 "results": [{
     "price": 5000
     "price": 6000
  {"id": "2",
 "results": [{
     "price": 15000
     "price": 16000

Then I render it with Express in the backend and Handlebars in front:

{{#each results as |auction|}}                    

     <span class="results__container--price">{{auction.price}} €</span>

(In reality, it's more complexe)

But I don't know how to use toLocaleString(). Maybe I have to loop through "prices in Express but I don't know how to do it. Is it possible to use it directly with Handlebars ?

1 answer

  • answered 2019-07-18 15:40 epascarello

    Use a helper function

    Handlebars.registerHelper('toLocaleString', function(number) {
      return number.toLocaleString()
    var source = document.getElementById("temp").innerHTML;
    var template = Handlebars.compile(source);
    var context = {
      title: "Hello",
      count: 123456789
    var html = template(context);
    document.getElementById("out").innerHTML = html;
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.1.2/handlebars.min.js"></script>
    <script id="temp" type="text/x-handlebars-template">
      <div class="test">
        <h2>{{toLocaleString count}}
    <div id="out"></div>