JavaScript模板引擎Template.js
阿新 • • 發佈:2018-12-18
template.js 一款 JavaScript 模板引擎,簡單,好用。提供一套模板語法,使用者可以寫一個模板區塊,每次根據傳入的資料,生成對應資料產生的HTML片段,渲染不同的效果。https://github.com/aui/artTemplate
1.語法
(1)、使用
引用簡潔語法的引擎版本,例如: <script src="dist/template.js"></script>
(2)、表示式
{{ 與 }} 符號包裹起來的語句則為模板的邏輯表示式。
(3)、輸出表達式
對內容編碼輸出: {{content}}
編碼可以防止資料中含有 HTML 字串,避免引起 XSS 攻擊。 (4)、條件表示式
{{if admin}}
<p>admin</p>
{{else if code > 0}}
<p>master</p>
{{else}}
<p>error!</p>
{{/if}}
(5)、遍歷表示式
無論陣列或者物件都可以用 each 進行遍歷。
亦可以被簡寫:{{each list as value index}} <li>{{index}} - {{value.user}}</li> {{/each}}
{{each list}}
<li>{{$index}} - {{$value.user}}</li>
{{/each}}
(6)、模板包含表示式
用於嵌入子模板。
{{include 'template_name'}}
子模板預設共享當前資料,亦可以指定資料:{{include 'template_name' news_list}}
(7)、輔助方法
使用template.helper(name, callback)註冊公用輔助方法:
template.helper('dateFormat', function (date, format) {
// ..
return value;
});
模板中使用的方式: {{time | dateFormat:'yyyy-MM-dd hh:mm:ss'}}
支援傳入引數與巢狀使用: {{time | say:'cd' | ubb | link}}
//格式化時間
template.helper('dateFormat', function (date, format) {
date = new Date(date);
var map = {
"M": date.getMonth() + 1, //月份
"d": date.getDate(), //日
"h": date.getHours(), //小時
"m": date.getMinutes(), //分
"s": date.getSeconds(), //秒
};
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;
});
boolFormat(data.importance)
template.helper('boolFormat', function (bool) {
return bool ? "是" : "否";
});