In the part1 we have seen how to create a Handlebarjs template and merge our REST API output with that template. In that output the date time values of Created and Modified is not well formatted. Below is the un-formatted output.
Image may be NSFW.
Clik here to view.
In this we will use Moment.js to do formatting.
Momemt.js
- js help us to parse, validate, manipulate and display dates in the JavaScript.
- It’s having rich set of methods to format the date string.
- You can download the moment.js from here
In the Handlebars we can create our custom methods to do additional functionality. Using the RegisterHelper we can create our custom method. Let’s create a method named “FormatDate” which will accept a parameter.
<script> Handlebars.registerHelper("FormatDate", function (date) { return moment(date.toString()).format('LL'); }); </script>
Some of the Moment.js Format strings;
Image may be NSFW.
Clik here to view.
To Call the Format Date function we need to change the HandleBars Template we have designed. Below is the updated template.
<script id="employees-template" type="text/x-handlebars-template"> <table> <thead> <th>Employee Name</th> <th>Designation</th> <th>Location</th> <th>Expert</th> <th>Created</th> <th>Modified</th> </thead> <tbody> {{#results}} <tr> <td>{{Title}}</td> <td>{{EmpDesignation}}</td> <td>{{Location}}</td> <td>{{SME}}</td> <td>{{FormatDate Created}}</td> <td>{{FormatDate Modified}}</td> </tr> {{/results}} </tbody> </table> </script>
Now the output of my page will be like below.
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
Clik here to view.
