art-template.js 时间戳格式化处理

2019-02-20  本文已影响0人  旅行者归来

当后台返回时间戳到前段的页面时,在模板引擎(art-template)需要如下处理。

首先在页面引入art-template.js文件 [下载地址](https://github.com/aui/art-template

定义一个js文件,将如下代码放到js文件中,然后将js文件引导到对应的页面

/**
 * 时间戳格式化方法
 * @param date
 * @param format
 * @returns {void | string}
 */
function dateFormat(date, format) {
    date = new Date(date);
    var map = {
        "M": date.getMonth() + 1, //月份
        "d": date.getDate(), //日
        "h": date.getHours(), //小时
        "m": date.getMinutes(), //分
        "s": date.getSeconds(), //秒
        "q": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
        var v = map[t];
        if (v !== undefined) {
            if (all.length > 1) {
                v = '0' + v;
                v = v.substr(v.length - 2);
            }
            return v;
        } else if (t === 'y') {
            return (date.getFullYear() + '').substr(4 - all.length);
        }
        return all;
    });
    return format;
};

在前段页面中定义模板代码

<script type="text/html" id="modelDataTbody_template">
 {{if data.time!= null}}
            <span>{{data.time| dateFormat:'yyyy-MM-dd h:mm:ss'}}</span>
 {{else}}
           <span></span>
 {{/if}}
</script>
 function getModelPersonList(nodeId) {
        $.ajax({
            type: 'Post',
            url: '${basePath!}gModel/getModelPersonList',
            data: {
                nodeId: nodeId
            },
            async: true,
            success: function (data) {
                if (data.success) {//显示历史版本列表数据
                    var html = template('modelPersonList_template', data);
                    $("#modelPersonList").html(html);
                } else if (!data.success) {
                    var html = template('modelPersonList_template', data);
                    $("#modelPersonList").html(html);//modelPersonList 为要将模板代码插入的标签容器
                } else {
                    layer.msg("系统异常,操作失败!", {icon: 2});
                }
            }
        });
    };
上一篇下一篇

猜你喜欢

热点阅读