<div id="header"></div><div class="contact" id="contact"></div><div id="footer"></div>先来讲讲id="contact"主体有些什么内容,html代码就不贴了,直接看下图:
handlebars的模版代码如下:
<script id="contact-template" type="text/x-handlebars-template"> <div class="tit">{{transformat info}}</div> {{#tit}} <span class="one">{{this}}</span> {{/tit}} {{#student}} <span class="one">{{@index}}</span><span class="one">{{name}}</span><span class="one">{{sex}}</span><span class="one">{{age}}</span><span class="one">{{sheight}}</span> {{/student}} </script>图片中的‘2016通讯录"用到了handlebars.registerHelper,代码如下:
Handlebars.registerHelper("transformat", function(value) { if(value == "通讯录") {return new Handlebars.SafeString("<font color="pink">2016通讯录</font>") } else {return "old通讯录"; } });注册一个helper,value是模版传进来的值,相当于jq的function(),new Handlebars.SafeString是为了防止把html标签输出为文本形式,就是jq下html()和text()的区别。
$("#contact").html(Handlebars.compile($("#contact-template").html())(data));如果有通用模版,就是一个模版要调用多次,上面的代码也可以这样写,方便调用:
var contact=Handlebars.compile($("#contact-template").html());$("#contact").html(contact(data));其中的data就是json数据,为了方便就自定义了:
var data = { "info": "通讯录", "tit": ["序号", "姓名", "性别", "年龄", "身高"], "student": [{"name": "张三","sex": "男","age": 18,"sheight": "175" }, {"name": "李四","sex": "男","age": 22,"sheight": "180" }, {"name": "妞妞","sex": "女","age": 18,"sheight": "165" }, {"name": "袁帅","sex": "男","age": 17,"sheight": "173" }] };最后效果图如下,其实和刚刚那个主体一样,就是有头有尾而已:
到这里其实handlebars的基础知识就讲解完了,已经能满足日常网站的需求,当然handlebars还有其他的一些功能,可以参考中文手册:
http://keenwon.com/992.html
未完待续,然后文件的头和尾怎么能拆分出来放在单独的页面中来引用呢?不然不可能每个页面都写一遍,以后要改就麻烦了(当然如果你前端用的是php、asp之类的动态语言,那么一下部分可以忽略不看,因为我用的是html+ajax来调用api接口的)然后只能百度新的东西,最终找到了require text.js,又一神器出现,天将降大任于斯人也,那么简单再来说说,看招:
text.js是require.js下的一个插件,我代码里都有。
我把头和尾拆分为两个单独的html文件,如下:
header.html
<script id="header-template" type="text/x-handlebars-template"> <div class="header"><span>首页</span><span>联系我们</span><span>关于我们</span></div></script>footer.html
<script id="footer-template" type="text/x-handlebars-template"> <div class="footer">CopyRight© 2015-2016</div></script>其实放在一个文件中也行,到时候自己体会。
<script type="text/javascript" src="js/require.js" data-main="js/main.js"></script>data-main其实是定义了一个入口文件,这个就不细说了,参考官方文档:
define(["text!../header.html", "text!../footer.html"], function(header, footer) { $("#header").html(header); $("#header").html(Handlebars.compile($("#header-template").html())); $("#footer").html(footer); $("#footer").html(Handlebars.compile($("#footer-template").html()));});text!../header.html中的text!表示把header.html文件引用进来以文本的形式,反正就是类似于php的include、require,把header.html和footer.html引用到index.html中。