jquery tmpl 详解

动态请求数据来更新页面是现在非常常用的方法,比如博客评论的分页动态加载,微博的滚动加载和定时请求加载等。

 

这些情况下,动态请求返回的数据一般不是已拼好的 HTML 就是 JSON 或 XML,总之不在浏览器端拼数据就在服务器端拼数据。不过,从传输量方面来看,返回 HTML 不划算,而在 web 传输方面,现在更多的是使用 JSON 而不是 XML。

浏览器端根据 JSON 生成 HTML 有个很苦恼的地方就是,结构不复杂的时候还好,结构一复杂,就想死了,需要很小心很小心地写出几乎无法维护的 JavaScript 代码。

因此一些用模版生成HTML的的框架相继出现jquery.tmpl 就是其中的一种,下面我们来详细介绍下jquery.tmpl的用法

jquery.tmpl的几种常用标签分别有:

${}{{each}}{{if}}{{else}}{{html}}

不常用标签

 {{=}},{{tmpl}} and {{wrap}}.

${}等同与{{=}}是输出变量 ${}里面还可以放表达式 (=和变量之间一定要有空格,否则无效

示例:

复制代码
<div id="div_demo">
</div>
<script id="demo" type="text/x-jquery-tmpl">
    <div style="margin-bottom:10px;">
      <span>${ID}</span>
      <span style="margin-left:10px;">{{= Name}}</span>
      <span style="margin-left:10px;">${Number(Num)+1}</span>
      <span style="margin-left:10px;">${Status}</span>
    </div>
</script>
<script type="text/javascript">
  var users = [{ ID: 'think8848', Name: 'Joseph Chan', Num: '1', Status: 1 }, { ID: 'aCloud', Name: 'Mary Cheung', Num: '2'}];
  $("#demo").tmpl(users).appendTo('#div_demo');
</script>
复制代码

 

 

{{each}} 提供循环逻辑,$value访问迭代变量 也可以自定义迭代变量(i,value)

示例:

复制代码
<div id="div_each">
</div>
<script id="each" type="text/x-jquery-tmpl"> 
    <h3>users</h3>
    {{each(i,user) users}}
        <div>${i+1}:{{= user.name}}</div>
        {{if i==0}}
            <h4>group</h4>
            {{each(j,group) groups}}
                <div>${group.name}</div>
            {{/each}}
        {{/if}}
    {{/each}}
    <h3>depart</h3>
    {{each departs}}
        <div>{{= $value.name}}</div>
    {{/each}}
</script> 
<script type="text/javascript">
  var eachData = { users: [{ name: 'jerry' }, { name: 'john'}], groups: [{ name: 'mingdao' }, { name: 'meihua' }, { name: 'test'}], departs: [{ name: 'IT'}] };
  $("#each").tmpl(eachData).appendTo('#div_each');
</script>
复制代码

 

{{if }} {{else}}提供了分支逻辑 {{else}} 相当于else if

示例:

 

复制代码
<div id="div_ifelse"></div>
<script id="ifelse" type="text/x-jquery-tmpl"> 
    <div style="margin-bottom:10px;"><span>${ID}</span><span style="margin-left:10px;">{{= Name}}</span>
        {{if Status}}
            <span>Status${Status}</span>
        {{else App}}
            <span>App${App}</span>
        {{else}}
            <span>None</span>
        {{/if}}
    </div>
</script> 
<script type="text/javascript">
  var users = [{ ID: 'think8848', Name: 'Joseph Chan', Status: 1, App: 0 }, { ID: 'aCloud', Name: 'Mary Cheung', App: 1 }, { ID: 'bMingdao', Name: 'Jerry Jin'}];
    $("#ifelse").tmpl(users).appendTo('#div_ifelse');
</script>
复制代码

 

{{html}} 输出变量html,但是没有html编码,适合输出html代码

 实例

复制代码
<div id="div_html"></div>
<script id="html" type="text/x-jquery-tmpl"> 
    <div style="margin-bottom:10px;">
    <span>${ID}</span>
    <span style="margin-left:10px;">{{= Name}}</span>
      ${html}
      {{html html}}
    </div>
</script> 
<script type="text/javascript">
  var user = { ID: 'think8848', Name: 'Joseph Chan', html: '<button>html</button>' };
   $("#html").tmpl(user).appendTo('#div_html');
</script>
复制代码

 

{{tmpl}} 嵌套模版

实例

复制代码
<div id="tmpl"></div>
<script id="tmpl1" type="text/x-jquery-tmpl">
    <div style="margin-bottom:10px;">
      <span>${ID}</span>
      <span style="margin-left:10px;">{{tmpl($data) '#tmpl2'}}</span>
    </div>     
</script>
<script id="tmpl2" type="type/x-jquery-tmpl">
    {{each Name}}${$value}  {{/each}}   
</script>
<script type="text/javascript">
  var users = [{ ID: 'think8848', Name: ['Joseph', 'Chan'] }, { ID: 'aCloud', Name: ['Mary', 'Cheung']}];
   $("#tmpl1").tmpl(users).appendTo('#tmpl');
</script>
复制代码

 

{{wrap}},包装器

实例

 

复制代码
<div id="wrapDemo">
    </div>
<script id="myTmpl" type="text/x-jquery-tmpl">
    The following wraps and reorders some HTML content:
    {{wrap "#tableWrapper"}}
        <h3>One</h3>
        <div>
            First <b>content</b>
        </div>
        <h3>Two</h3>
        <div>
            And <em>more</em> <b>content</b>...
        </div>
    {{/wrap}}
    </script>
<script id="tableWrapper" type="text/x-jquery-tmpl">
    <table cellspacing="0" cellpadding="3" border="1"><tbody>
        <tr>
            {{each $item.html("h3", true)}}
                <td>
                    ${$value}
                </td>
            {{/each}}
        </tr>
        <tr>
            {{each $item.html("div")}}
                <td>
                    {{html $value}}
                </td>
            {{/each}}
        </tr>
    </tbody></table>
    </script>
 <script type="text/javascript">
        $(function () {
            $('#myTmpl').tmpl().appendTo('#wrapDemo');
        });
    </script>
复制代码

 

 

 

$data $item $item代表当前的模板;$data代表当前的数据。

 

 实例:

复制代码
<div id="div_item_data"></div>
<script id="item_data" type="text/x-jquery-tmpl"> 
     <div style="margin-bottom:10px;">
    <span>${$data.ID}</span>
    <span style="margin-left:10px;">${$item.getName(" ")}</span>
   </div>
</script> 
<script type="text/javascript">
   var users = [{ ID: 'think8848', Name: ['Joseph', 'Chan'] }, { ID: 'aCloud', Name: ['Mary', 'Cheung']}];
     $("#item_data").tmpl(users,
                {
                getName: function (spr) {
                   return this.data.Name.join(spr);
                }
                }).appendTo('#div_item_data');
</script>
复制代码

 

 $.tmplItem()方法,使用这个方法,可以获取从render出来的元素上重新获取$item

实例

<script type="text/javascript">
  $('#demo').delegate('div', 'click', function () {
                var item = $.tmplItem(this);
                alert(item.data.Name);
            });
</script>

 

Tmpl提供了几种tag:

${}:等同于{{=}},是输出变量,通过了html编码的。
{{html}}:输出变量html,但是没有html编码,适合输出html代码。
{{if }} {{else}}:提供了分支逻辑。
{{each}}:提供循环逻辑,$value访问迭代变量。

jquery tmpl的使用方法:

模板定义:

方法一:

?
1
2
3
4
5
<script id= "movieTemplate" type= "text/x-jquery-tmpl" >
<li>
<b>${Name}</b> (${ReleaseYear})
</li>
</script>

方法二:

?
1
2
3
4
function makeTemplate(){
var markup='<li><b>${Name}</b> (${ReleaseYear})</li>‘;
$.template(“movieTemplate”, markup);
}

DATA:

?
1
2
3
4
5
var movies = [
{ Name: "The Red Violin" , ReleaseYear: "1998" },
{ Name: "Eyes Wide Shut" , ReleaseYear: "1999" },
{ Name: "The Inheritance" , ReleaseYear: "1976" }
];

Script:

?
1
2
$( "#movieTemplate" ).tmpl( movies )
.appendTo( "#movieList" );

实例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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<!DOCTYPE html>
<html>
<head>
</head>
<body>
 
<ul class= "param-list" ></ul>
 
<script type= "text/x-jquery-tmpl" id= "new-param-tmpl" >
<li rel= "${num}" >
<input type= "text" name= "key[${num}]" value= "${key}" placeholder= "key" /> =
<input type= "text" name= "value[${num}]" value= "${value}" placeholder= "value" />
<button type= "button" class= "button small remove-param" ><img src= "http://mediacdn.disqus.com/1338845651/images/v3/icon/16/69.png" height= "12" alt= "" /></button>
<button type= "button" class= "button small add-param" ><span><img src= "http://mediacdn.disqus.com/1338845651/images/v3/icon/16/13.png" height= "12" alt= "" /></button>
</li>
</script>
 
<script>
$( function (){
function addParam(key, value) {
var param_list = $( '.param-list' );
var num = param_list.find( 'li' ).length;
 
// build a template to clone the current row
var built = $( '#new-param-tmpl' ).tmpl({
num: num,
key: key || '' ,
value: value || '' ,
});
if (key) param_list.prepend(built);
else param_list.append(built);
 
param_list.find( 'li:not(:last) .add-param' ).hide();
param_list.find( 'li:last .add-param' ).show();
param_list.find( 'li:not(:last) .remove-param' ).show();
param_list.find( 'li:last .remove-param' ).hide();
}
 
// bind events
$( '.param-list .remove-param' ).live( 'click' , function (){
$( this ).parent().remove();
return false ;
});
$( '.param-list .add-param' ).live( 'click' , function (){
addParam();
return false ;
});
 
addParam();
})
</script>
</body>
</html>

实例2

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<ul id= "movieList" ></ul>
 
<script id= "movieTemplate" type= "text/x-jquery-tmpl" >
<li><b>${Name}</b> (${ReleaseYear})</li>
</script>
 
<script type= "text/javascript" >
var movies = [
{ Name: "The Red Violin" , ReleaseYear: "1998" },
{ Name: "Eyes Wide Shut" , ReleaseYear: "1999" },
{ Name: "The Inheritance" , ReleaseYear: "1976" }
];
 
// Render the template with the movies data and insert
// the rendered HTML under the "movieList" element
$( "#movieTemplate" ).tmpl( movies )
.appendTo( "#movieList" );
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值