embed moment.js formatting in handlebars templates

半城伤御伤魂 提交于 2019-12-10 23:34:51

问题


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


回答1:


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>



来源:https://stackoverflow.com/questions/37654702/embed-moment-js-formatting-in-handlebars-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!