template.js的使用心得

template.js的使用心得
template.js是一款JavaScript模板引擎,用来渲染页面的。

原理:提前将Html代码放进编写模板

中,当需要渲染页面时,在js里这样调用:

1
var tpl = document.getElementById(‘tpl’).innerHTML; template(tpl, data});
template.js可以使用命令安装,也可以在git上面下载:https://github.com/yanhaijing/template.js

template.js开始标签默认为<%,结束标签默认为%>,显示数据为<%= i %>。

下面是使用template.js v0.7.1版本的实验结果:

1、遍历数组显示数据:

复制代码

复制代码

2、模拟子模板

复制代码

模拟子模版
<script id="tpl" type="text/html">
   <h1>国内新闻</h1>
   <%:=newsListTpl({list: list1, tpl: childTpl})%>
   <h1>国际新闻</h1>
   <%:=newsListTpl({list: list2, tpl: childTpl})%>
复制代码

3、子模板里面的子模板

复制代码

模拟子模版
<script id="tpl" type="text/html">
 <h1>国内新闻</h1>
 <%:=listTpl({list: list1, tpl: subChildTpl})%>
 <h1>国际新闻</h1>
 <%:=listTpl({list: list2, tpl: subChildTpl})%>
复制代码

4.foreach循环获取数据

复制代码

复制代码

5、registerFunction

复制代码

复制代码

6、registerModifier

复制代码

var html = template(document.getElementById(‘tpl’).innerHTML,{});
document.getElementById(‘wp’).innerHTML = html;

复制代码

猜你喜欢

转载自blog.csdn.net/sinat_40390240/article/details/89887803
今日推荐