使用art-template我們避免了N多的字元串拼接,但遇到日期格式化該如何處理呢?
我們定義一個處理日期格式化的JS函數,放到一個單獨的檔案dateformate.js。
/**
* 對日期進行格式化,
* @param date 要格式化的日期
* @param format 進行格式化的模式字元串
* 支援的模式字母有:
* y:年,
* M:年中的月份(1-12),
* d:月份中的天(1-31),
* h:小時(0-23),
* m:分(0-59),
* s:秒(0-59),
* S:毫秒(0-999),
* q:季度(1-4)
* @return String
* @author yanis.wang
* @see http://yaniswang.com/frontend/2013/02/16/dateformat-performance/
*/
function dateFormat(date, format) {
date = new Date(date);
var map = {
"M": date.getMonth() + , //月份
"d": date.getDate(), //日
"h": date.getHours(), //小時
"m": date.getMinutes(), //分
"s": date.getSeconds(), //秒
"q": Math.floor((date.getMonth() + ) / ), //季度
"S": date.getMilliseconds() //毫秒
};
format = format.replace(/([yMdhmsqS])+/g, function(all, t){
var v = map[t];
if(v !== undefined){
if(all.length > ){
v = '0' + v;
v = v.substr(v.length-);
}
return v;
}
else if(t === 'y'){
return (date.getFullYear() + '').substr( - all.length);
}
return all;
});
return format;
};
使用:
// art-template日期格式化
template.defaults.imports.dateFormat = dateFormat;
在頁面先定義模闆html
<script id="mqMonitorRecordTemplate" type="text/html">
{{each list item index}}
<tr>
<td>{{index+1}}</td>
<td>{{item['serverIp']}}</td>
<td><%=#dateFormat(item['createTime'],'yyyy/MM/dd hh:mm')%></td>
<td>{{item['type']}}</td>
<td>{{item['reason']}}</td>
</tr>
{{/each}}
</script>
在
<script>
中先編譯上面的模闆
var render = template.compile($('#mqMonitorRecordTemplate').html());
使用(一個分頁的例子):
function mqMonitorRecordSearch() {
var pageNo = $('[name=pageNo]').val();
var data = {
serverIp: $('[name=serverIp]').val(),
type: $('[name=type]').val()
};
$.get('[[${ctx}]]/mqMonitor/search/' + pageNo,data,function(r) {
if (r.returnCode == ) {
$('#mqMonitorRecordTbl tbody').html(render(r.data.pager)); // 這行代碼是使用模闆渲染,擷取渲染後的html,設定到tbody。
$('#DataTables_Table_1_paginate').html(r.data.pageHtml);
}
else {
layer.alert(r.errMsg);
}
});
}