template.js 一款 JavaScript 模板引擎,简单,好用。提供一套模板语法,用户可以写一个模板区块,每次根据传入的数据,生成对应数据产生的HTML片段,渲染不同的效果。https://github.com/aui/artTemplate
1.语法
(1)、使用
引用简洁语法的引擎版本,例如: <script src="dist/template.js"></script>
(2)、表达式
{{ 与 }} 符号包裹起来的语句则为模板的逻辑表达式。
(3)、输出表达式
对内容编码输出: {{content}}
不编码输出: {{#content}}
编码可以防止数据中含有 HTML 字符串,避免引起 XSS 攻击。
{{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 ? "是" : "否";
});