数据交互
模板引擎采用Handlebars
,github地址:* Handlebars.js
1.内部模板:采用script标签作为模板标签,script类型为type="text/x-handlebars-template"
。使用Handlebars.compile(t("#template").html())(data)
进行渲染。
2.外部模板:调用外部的html文件,t(".current ul").renderAppend("template_render.html", data2);
采用renderAppend
直接渲染,第二个参数为数据。
示例:
<script id="template" type="text/x-handlebars-template">
{{#boys}}
<li>
<a href="javascript:;" class="link_item">
<div class="item item-trim">
<div class="item_left">
<div class="item-icon-l-b bg_blue">
<i class="icon ion-android-apps"></i>
</div>
</div>
<div class="item_center">
<div class="item-content">{{name}}</div>
</div>
</div>
</a>
</li>
{{/boys}}
</script>
<script>
var data = {boys: [{name: "内部模板渲染"},{name: "内部模板渲染"},{name: "内部模板渲染"},{name: "内部模板渲染"},{name: "内部模板渲染"}]};
var data2 = {boys: [{name: "外部模板渲染"},{name: "外部模板渲染"},{name: "外部模板渲染"},{name: "外部模板渲染"},{name: "外部模板渲染"}]};
function update(){
t(".current ul").append(Handlebars.compile(t("#template").html())(data));
}
function update2(){
t(".current ul").renderAppend("template_render.html", data2);
}
</script>
3.模板引擎插件helper,为Handlebars做逻辑扩充。github地址:* Handlebars-Helpers 具体方法:
<script>
{{#is x}} ... {{else}} ... {{/is}}
{{#is x "not" y}} ... {{else}} ... {{/is}}
{{#is 5 ">=" 2}} ... {{else}} ... {{/is}}
// Loose equality checking
{{#is x y}} ... {{else}} ... {{/is}}
{{#is x "==" y}} ... {{else}} ... {{/is}}
{{#is x "!=" y}} ... {{else}} ... {{/is}}
{{#is x "not" y}} ... {{else}} ... {{/is}}
// Strict equality checking
{{#is x "===" y}} ... {{else}} ... {{/is}}
{{#is x "!==" y}} ... {{else}} ... {{/is}}
// Greater/Less Than
{{#is x ">" y}} ... {{else}} ... {{/is}}
{{#is x ">=" y}} ... {{else}} ... {{/is}}
{{#is x "<" y}} ... {{else}} ... {{/is}}
{{#is x "<=" y}} ... {{else}} ... {{/is}}
// In comma separated list, or array
{{#is x "in" "foo,bar"}} ... {{else}} ... {{/is}}
{{#is x "in" anArray}} ... {{else}} ... {{/is}}
</script>
4.建议使用方式: (1)项目根目录:template.html 保存所有模板文件。 (2)js目录下:script.js 放置所有服务器请求,同时进行渲染。 也可以根据对象创建目录,分开保存到相应目录中。