artTemplate模版语法氛围简洁语法和原生语法,最直接的区别在于,首先使用不同的语法需要引入对应的文件,在标签写法上采用简洁语法使用{{var}},采用原生语法使用<%var%>.
示例:
1,变量解析
<div id="content"></div>
<script type="text/html" id="contentTpl">
<div>{{name}}</div>
</script>
<script type="text/javascript">
var data={
name:"vito",
list:[{age:20,sex:"man"},{age:19,sex:"woman"}]
}
var html=template("contentTpl",data);
document.getElementById("content").innerHTML=html;
</script>
2,循环以及嵌套
<div id="content"></div>
<script type="text/html" id="contentTpl">
{{each list as value i}}
<div>{{i+1}}.age:{{value.age}},sex:{{value.sex}}</div>
{{/each}}
//循环嵌套
{{each goods as val j}}
<div>
{{each val as v i}}
<div>{{i+1}},{{v.name}}:{{v.price}}</div>
{{/each}}
</div>
{{/each}}
</script>
<script type="text/javascript">
var data={
name:"vito",
list:[{age:20,sex:"man"},{age:19,sex:"woman"}],
goods:[[{price:20,name:"banana"},{price:14,name:"apple"}],[{price:2,name:"cup"},{price:3000,name:"computer"}]]
}
var html=template("contentTpl",data);
document.getElementById("content").innerHTML=html;
</script>
3,条件判断if else
<div id="content"></div>
<script type="text/html" id="contentTpl">
<div>{{name}}</div>
{{each list}}
{{if $value.age<20}}
<div>this guy is not {{name}}</div>
{{else}}
<div>{{name}}is{{$value.age}}years old ,he is a {{$value.sex}}</div>
{{/if}}
{{/each}}
</script>
<script type="text/javascript">
var data={
name:"vito",
list:[{age:20,sex:"man"},{age:19,sex:"woman"}]
}
var html=template("contentTpl",data);
document.getElementById("content").innerHTML=html;
</script>