ijgames

今天再给大家带点html5前端开发的干货模板“text/tpl”怎么用 script template怎么用

text/tpl 顾名思义就是模板,其实和C++模板函数类似的作用,就是利用他生成一个HMTL内容,然后append或者替换html里面

有什么好处,假如后端返回来的数据都是一样的,但是需要生成不同的内容时候,这个时候使用模板减少代码量是最好的,我只需要定义不同模板,调用同一个id就写同一个生成代码就行了,这就是模板好处,就不用写那么多js的字符串++操作,烦死人了

下面介绍怎么用

template定义

1、首页模板

<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、模板二定义

<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();

我只需要写同一个生成代码即可

      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);
                }
            });

比如可以看我的html5网站怎么用,需要使用chrome浏览器切换到移动模式审核元素才可以看到 ,是不是看起来代码简单了好多啊,不用为每一个内容做不同的生成操作。一统天下

这里使用模板需要引用mustache.js

//cdn.bootcss.com/mustache.js/2.2.1/mustache.min.js

下面介绍下mustache一些简单知识,详情可以具体去百度了解更多谢谢。

{{#posts}} {{/posts}} 因为我的数据结构是一个个post组成的数组,post 有link  title 等属性,所以这标签意思是循环使用,每个post生成一个#是开始/是这个post结束,里面的
{{link}} {{title}}是把当前的这个post的属性填进去。具体关于mustache用法可以去百度了解更多。

下一期将介绍瀑布流怎么制作

 

posted @ 2016-08-26 10:35  ijgames  阅读(2166)  评论(1编辑  收藏  举报
33小游戏IJ遊戲