<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title></title>
<style>
html,
body,
ul,
li {
margin: 0;
padding: 0;
border: 0;
}
</style>
</head>
<body>
<div id="content">
</div>
<script src="artTemplate.js">
</script>
<!--创建模版-->
<script id="test" type="text/html">
<ul>
{{each list}}
{{if $index==0}}
<li>xx0</li>
{{else if $index==1}}
<li>xx1</li>
{{else if $index==2}}
<li>xx2</li>
{{else}}
<li>{{$index+1}}</li>
{{/if}}
{{/each}}
</ul>
<div>{{xx(n)}}</div>
<div>{{Math_PI()}}</div>
<div>{{time | dateFormat:'yyyy年 MM月 dd日 hh:mm:ss'}}</div>
<div>{{dateFormat(time,'yyyy年 MM月 dd日 hh:mm:ss')}}</div>
<div>{{plus(a,b)}}</div>
<div>{{plus(c,d)}}</div>
</script>
<!--模版的辅助方法-->
<script>
template.helper("xx", function(a) {
return 10 + "--" + a;
});
template.helper('dateFormat', function(date, format) {
console.warn(date);
date = new Date(date);
console.log(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;
});
template.helper('Math_PI', function() {
return Math.PI * Math.random();
});
template.helper('plus', function(a, b) {
return a + b;
});
var data = {
time: (new Date).toString(),
n: 123,
a: 20,
b: 30,
c: '22',
d: '33',
list:[1,2,3,4,5,6,7,8,9]
};
<!--模版渲染-->
var html = template("test", data);
<!--添加到页面-->
document.getElementById("content").innerHTML = html;
</script>
</body>
</html>