Html模板引擎Handlerbars使用demo
1.自定义demo
<html>
<head>
<script src="./handlebars-v4.0.12.js"></script>
</head>
<body>
<ul id='tmpContainer1'></ul>
<ul id = 'tmpContainer2'></ul>
<!--案例1-->
<script id='tmp1' type="text/x-handlebars-template">
{{#each people}}
<li>{{name}}</li>
{{/each}}
</script>
<script type="text/javascript">
//1.定义模板填充用的参数
var content = {
people : [
{name:'aa', age: 12},
{name:'bb', age: 12},
{name:'cc', age: 15},
{name:'dd', age: 16},
]
}
//2.定义模板
var template1 = Handlebars.compile(document.getElementById("tmp1").innerHTML);
//3.模板套用填充参数,返回模板填充结果
var html1 = template1(content);
//4.将模板填充的结果嵌入到页面响应位置
document.getElementById("tmpContainer1").innerHTML = html1;
</script>
<!--======================================================-->
<!--案例2-->
<script id = 'tmp2' type="text/x-handlebars-template">
{{#each people}}
<li>{{combine this}}</li>
{{/each}}
</script>
<script>
var content = {
people : [
{name:'aa', age: 12},
{name:'bb', age: 12},
{name:'cc', age: 15},
{name:'dd', age: 16},
]
}
//注意helper的注册要先于 Handlebars.compile()的执行,否则报错。
Handlebars.registerHelper('combine',function(item){
return item.name + ' '+ item.age;
})
var template2 = Handlebars.compile(document.getElementById("tmp2").innerHTML);
var html2 = template2(content);
document.getElementById("tmpContainer2").innerHTML = html2;
</script>
</body>
</html>
2. 更多demo(较详细介绍)请参看如下博客
========
zhcgis 版权所有,引用请注明出处!
========