Search code examples
javascripthandlebars.jshandlebarshelper

Formatting Date using handlerbar helpers


I wrote a helper for handlebars

Handlebars.registerHelper('timestamp', function(timeFormat) {
        return moment().format(timeFormat);
});

And I'm calling this with

{{{timestamp YYYYMMDDHHMMSS}}}

But, this doesn't work. timeFormat is undefined.

How do I get timeFormat in that helper function?


Solution

  • As mentioned in my comment, you have to add a string as a param from the template. I assume that using YYYYMMDDHHMMSS without double quotes, you're using an object as param, and thus the format-function of momentjs, expecting a string, does not work as expected.

    So, you have to call {{{timestamp "YYYYMMDDHHMMSS"}}} from your handlebars file.

    Btw: Here's a little gist I found, doing some more checks: https://gist.github.com/stephentcannon/3409103 if you want to work with moment() instead of a Date as first param, just remove the first param.