text/tpl 顾名思义就是模板,其实和C++模板函数类似的作用,就是利用他生成一个HMTL内容,然后append或者替换html里面
有什么好处,假如后端返回来的数据都是一样的,但是需要生成不同的内容时候,这个时候使用模板减少代码量是最好的,我只需要定义不同模板,调用同一个id就写同一个生成代码就行了,这就是模板好处,就不用写那么多js的字符串++操作,烦死人了
下面介绍怎么用
template定义
1、首页模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 < script type="text/tpl" id="game-tpl"> {{#posts}} < div class="item item-box"> < div class="item-top"> < a href="{{link}}" title="{{title}}"> < div class="pic"> < img data-original="{{thumb}}" width="60" height="60" alt="{{title}}"> </ div > </ a > < div class="info"> < a href="{{link}}" title="{{title}}"> < div class="name">{{title}}</ div > </ a > http://www.33xyx.com/" title="{{title}}"> < div class="dl-btn"> < span >在线玩</ span > </ div > </ a > </ div > </ div > < div class="message"> < div class="byte"> {{#cat_tag}} < a class="line" href="link">{{name}}</ a > {{/cat_tag}} </ div > </ div > </ div > {{/posts}} </ script >
2、模板二定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 < script type="text/tpl" id="game-tpl"> {{#posts}} < div class="item"> < div class="pic"> < a href="{{link}}" title="{{title}}"> < img data-original="{{thumb}}" width="66" height="66" alt="{{title}}"> </ a > </ div > < a href="http://www.33xyx.com/dongzuo/" class="info" title="{{title}}"> < div class="name">{{title}}</ div > < div class="attr"> {{#cat_tag}} < div class="kind">{{name}}</ div > {{/cat_tag}} </ div > < div class="star"> < div class="star-num" style="width: 90%;"> </ div > </ div > </ a > < div class="down"> < a class="pkg" href="33xyx" title="{{title}}">在线玩</ a > </ div > </ div > {{/posts}} </ script >
这个模板脚本标签一般放到</body>下面,虽然接受的后端的数据结构都是一样,但是我可以生成不同的内容,而不需要写一大堆js的字符串++操作,
$post['thumb'] = $img_src[0];$post['title'] = get_the_title();$post['link'] = get_permalink();我只需要写同一个生成代码即可 1 2 3 4 5 6 7 8 9 10 11 12 13 14 jQuery.ajax({ type: 'POST', url: http://www.33xyx.com/yizhi/, data: { action: 'load_more', }, success: function (data) { console.log(data); var template = $('#game-tpl').html(); Mustache.parse(template); var rendered = $(Mustache.render(template, data)); $("#J-games").append(rendered); } });比如可以看我的33小游戏怎么用,需要使用chrome浏览器切换到移动模式审核元素才可以看到 ,是不是看起来代码简单了好多啊,不用为每一个内容做不同的生成操作。一统天下
这里使用模板需要引用mustache.js
//cdn.bootcss.com/mustache.js/2.2.1/mustache.min.js下面介绍下mustache一些简单知识,详情可以具体去百度了解更多谢谢。 1 {{#posts}} {{/posts}} 因为我的数据结构是一个个post组成的数组,post 有link title 等属性,所以这标签意思是循环使用,每个post生成一个#是开始/是这个post结束,里面的 {{link}} {{title}}是把当前的这个post的属性填进去。具体关于mustache用法可以去百度了解更多。