Search code examples
asp.nethandlebars.jsmomentjs

embed moment.js formatting in handlebars templates


I am trying get Moment.js date-time formating as part of my handlebars template.

Actual Sample:

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div id="hb-content"></div>

    <script id="hb-template" type="text/x-handlebars-template">
        <small>Last restarted:</small>
        <code>moment({{last_started}}).format('dddd, MMMM Do');</code>
        <code>moment({{last_started}}).format('h:mma');</code>
    </script>

    <script type="text/javascript">
        var temp = document.getElementById("hb-template").innerHTML;
        var template = Handlebars.compile(temp);
        var html = template({
            last_started: "/Date(1463152740000)/"
        })

        document.getElementById('hb-content').innerHTML = html;
    </script>
</asp:Content>

Output:

Last restarted: moment(/Date(1463152740000)/).format('dddd, MMMM Do'); moment(/Date(1463152740000)/).format('h:mma');

Expected Output:

Last restarted: Friday, May 13th 9:15pm


Solution

  • Got it:

    <script id="hb-template" type="text/x-handlebars-template">
        <small>Last restarted:</small>
        <code>{{formatDate current_date 'dddd, MMMM Do'}}</code>
        <code>{{formatDate current_date 'h:mm:ssa'}}</code>
    </script>
    
    <script type="text/javascript">
        $(function () {
            Handlebars.registerHelper("formatDate", function (datetime, format) {
                return moment(datetime).format(format);
            });
    
            var temp = document.getElementById("hb-template").innerHTML;
            var template = Handlebars.compile(temp);
            var html = template({
                last_started: "/Date(1463152740000)/",
                current_date: new Date() //"/Date(1463152740000)/"
            })
    
            document.getElementById('hb-content').innerHTML = html;
        });
    </script>