Handlebars.js helper in #each loop returns same results?

300 views Asked by At

I'm trying to format my dates using a handlebars registered momentjs helper inside an #each loop. The registered helper looks like this :


    Handlebars.registerHelper('dateFormat', function(context) {
      if (window.moment) {

        return moment(Date(context)).format("MMM Do, YYYY");
      }else{
        return context;
      };
    });

The handlebars loop looks like this

{{#each controller}}
{{{body}}}
{{{dateFormat date}}}
{{/each}}

The JSON that is being looped is in this


    {
       "idea":[
          {
             "_id":"548eeebeda11ffbe12000002",
             "body":"cow",
             "tag":"cow",
             "date":"2014-12-15T14:22:54.088Z"
          },
          {
             "_id":"548eeec2da11ffbe12000003",
             "body":"cow",
             "tag":"moose",
             "date":"2014-10-15T14:22:58.947Z"
          }
       ]
    }

So the problem that I'm having is that it loops just fine it just doesn't evaluate the helper correctly.

The results that I'm getting look like this

cow Dec 15th, 2014
cow Dec 15th, 2014
The dates are always the same.

Its should to look like this
cow Dec 15th, 2014
cow Oct 15th, 2014

2

There are 2 answers

0
mbejda On

I got it working using this.get('date');


    Handlebars.registerHelper('dateFormat', function(context) {
          if (window.moment) {

            return moment(this.get('date')).format("MMM Do, YYYY");
          }else{
            return context;
          };
        });

0
Cory Danielson On

The original issue was that you weren't instantiating a new Date inside of each iteration of the loop.

Handlebars.registerHelper('dateFormat', function(context) {
  if (window.moment) {
               // new Date() !, calling Date("anything") returns current date
    return moment(new Date(context)).format("MMM Do, YYYY");
  }else{
    return context;
  };
});

Both dates returned the expected result:

new Date("2014-10-15T14:22:58.947Z")
> Wed Oct 15 2014 09:22:58 GMT-0500 (CDT)
new Date("2014-12-15T14:22:54.088Z")
> Mon Dec 15 2014 08:22:54 GMT-0600 (CST)