JS之模板技术(aui / artTemplate)

来源:互联网 发布:arc map空间数据编辑 编辑:程序博客网 时间:2024/05/23 12:49

artTemplate是个好东西啊,一个开源的js前端模板引擎,使用简单,渲染效率特别的高。

我经常使用这个技术来在前端动态生成新闻列表,排行榜,历史记录等需要在前端列表显示的信息。

下面是artTemplate的下载链接:

https://github.com/aui/artTemplate

因为artTemplate比较简单,容易上手,项目的例子,文档又比较齐全,大家有需要可以直接参考官方文档,例子进行深入了解,

我这里就这是用简单常用的,用于快速上手的一个例子吧!

先说明,我是下载artTemplate工程项目src目录下的template.js的

内容大概为:

...略

var template = function (id, content) {
    return template[
        typeof content === 'object' ? 'render' : 'compile'
    ].apply(template, arguments);
};

...略

其中主要也就是使用到这个函数。

前端的页面内容主要为

<body>
  <center><h1><font color="#f00">这是template模板技术使用示例</font></h1></center>
  <script id="personListId" type="text/html">
<font color="#f00" size="24">
<$for (var i = 0; i < personList.length; i++) {$>
客户姓名:<$=personList[i].name$>&nbsp;&nbsp;&nbsp;客户年龄:<$=personList[i].age$><br/>
<$}$>
</font>
</script>
  <div id="templateContent"></div>
    <script type="text/javascript" src="js/jquery-1.8.2.js"></script>
    <script type="text/javascript" src="js/template.js"></script>
    <script type="text/javascript" src="js/page/index.js"></script>
  </body>

其中我使用了jquery,template,这两个都可以上网下载,放置到对应目录就ok。

下面这段代码使用模板技术进行for循环,格式为:

<$$>对内可写js代码,<$=val$>是输出js的变量val的值,

看着这个for循环,需要注意三点:

1)<script></script>必须标上唯一id,如<script id="personListId"></script>

2)<script></script>的type的值是text/html,而不是text/javascript

3)personList这个js变量从哪里来的,这里先留个疑问吧

4)对于这个列表要怎么显示,你就对应怎么写就好,这里是最简单的显示客户姓名和客户年龄,也没带什么图片,样式之类的

      客户姓名:<$=personList[i].name$>&nbsp;&nbsp;&nbsp;客户年龄:<$=personList[i].age$><br/>

<script id="personList" type="text/html">
<font color="#f00" size="24">
<$for (var i = 0; i < personList.length; i++) {$>
客户姓名:<$=personList[i].name$>&nbsp;&nbsp;&nbsp;客户年龄:<$=personList[i].age$><br/>
<$}$>
</font>
</script>

接下来就是写自己的js代码,使用template模板技术,动态渲染以上前端代码

代码写在js/page/index.js这个文件中,内容为:

$(function(){
var persons= [
{
name : "11111111111",
age : 1111111111111111
},
{
name : "2222222222",
age : 2222222222
},
{
name : "33333333333",
age : 333333333333
}
];//自定义的json格式数据,实际应用中一般都是使用ajax请求服务器获取json格式的数据,不知道从js的哪个版本起,js已经内置支持json格式的数据

var html = template('personListId',{personList : persons});//看着这行代码,是否注意到之前提到的personListId和personList 已经在这里使用上和定义好了

$('#templateContent').html('').html(html);//jquery的用法,目的就是将动态生成的内容(html)填充到id为templateContent的div

});


write less,do more,i like




0 0
原创粉丝点击