handlebars.js模版引擎随记

前台的模版引擎有许多种,相比较而言 我个人更觉得handlebars更为轻便

首先github上下载自新版本的handelbars.js http://handlebarsjs.com

下载下来之后呢 我们需要在页面引入js

1 <script type="text/javascript" src="script/jquery.js"></script>
2 <script type="text/javascript" src="script/handlebars-1.0.0.beta.6.js"></script>

引入之后我们需要在html中定义数据占位 在handlebars中最基本的就是使用 {{ }} 包裹 例如{{value}} handlebars模块会自动匹配相对应的值,对象或者函数

1 <div class="demo">
2     <h1>{{name}}</h1>
3     <p>{{content}}</p>
4 </div>

你也可以单独的制作一个模版,用id或者class来确定唯一性,type是固定的 不可缺少

1 <script id="tpl" type="text/x-handlebars-template">
2     <div class="demo">
3             <h1>{{title}}</h1>
4             <p>{{content.title}}</p>
5     </div>
6 </script>

在js中使用handlebars.compile()来预编译模版

1 //用jquery获取模板
2 var tpl  =  $("#tpl").html();
3 var template = Handlebars.compile(tpl);
4 //模拟json数据
5 var context = { name: "zhaoshuai", content: "learn Handlebars"};
6 //匹配json内容
7 var html = template(context);

一般我们使用模版引擎最主要还是解决数据的遍历问题 所以 handlebars里面有内置的表达式 each 我们可以利用 {{#each name}}来遍历列表块的内容,用this来引用遍历的元素, name是数组

1 <ul>
2       {{#each name}}
3         <li>{{this}}</li>
4       {{/each}}
5 </ul>

对应json是:

1 {
2   name: ["html","css","javascript"]
3 };

编译后:

1 <ul>
2   <li>JavaScript</li>
3   <li>HTML</li>
4   <li>CSS</li>
5 </ul>

在最后必须要提的是 引入的时候一定要放在 jquery的后面 不然handlebars里面有的方法会报错的

再补一点 模版内的 注释

写法如下:

1 {{! handlebars comments }}

 最后贴上一张 写好的代码

posted @ 2018-02-08 17:31  Solo李  阅读(196)  评论(0编辑  收藏  举报