jQuery .tmpl(), .template()学习

来源:互联网 发布:vb窗体控件 编辑:程序博客网 时间:2024/05/18 15:24

昨晚无意中发现一个有趣的jQuery插件.tmpl(),其文档在这里。

官方解释对该插件的说明:将匹配的第一个元素作为模板,render指定的数据,签名如下:

.tmpl([data,][options])

其中参数data的用途很明显:用于render的数据,可以是任意js类型,包括数组和对象。options一般情况下都是选项了,官方指出,此处的options是一个用户自定义的键值对的map,继承自tmplItem数据结构,适用于模板render动作期间。

在这里可以下载到最新的tmpl插件,值的一提的是,官方同时也说明了,tmpl目前是beta版,使用需谨慎..

好吧,先来一个最直观的例子:

<%@ Page Language="C#" AutoEventWireup="true" %>
 
<!DOCTYPE html>
<html>
<head>
    <title>jquery template demo</title>
    <linkrel="stylesheet"href="content/site.css"type="text/css"/>
    <linkrel="stylesheet"href="content/jquery.ui.css"type="text/css"/>
    <scripttype="text/javascript"src="scripts/jquery.js"></script>
    <scripttype="text/javascript"src="scripts/jquery.ui.js"></script>
    <scripttype="text/javascript"src="scripts/jquery.tmpl.js"></script>
    <scriptid="myTemplate"type="text/x-jquery-tmpl">
        <tr><td>${ID}</td><td>${Name}</td></tr>
    </script>
    <scripttype="text/javascript">
        $(function () {
            var users = [{ ID: 'think8848', Name: 'Joseph Chan' }, { ID: 'aCloud', Name: 'Mary Cheung'}];
            $('#myTemplate').tmpl(users).appendTo('#rows');
        });
    </script>
    <styletype="text/css">
        body
        {
            padding: 10px;
        }
        table
        {
            border-collapse: collapse;
        }
    </style>
</head>
<body>
    <tablecellspacing="0"cellpadding="3"border="1">
        <tbodyid="rows">
        </tbody>
    </table>
</body>
</html>

例子虽然很小也很简单,但我觉得这个已经很有用了。

当然,.tmpl()还可以使用来自远端的数据,比如说服务:

public ActionResult SampleData()
{
    var json =newJsonResult();
    json.Data =new[] {new { ID = "remote1", Name = "abcd" }, new{ ID ="remote2", Name ="efg"} };
    json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    returnjson;
}

这是一个MVC的Action,我把它当做是一个提供数据的服务,然后js代码如下:

$('#btnAjax').click(function() {
    $.getJSON('@Url.Action("SampleData", "Home")',function(json) {
        $('#rows').empty();
        $('#myTemplate').tmpl(json).appendTo('#rows');
    });
});

效果:

定义模板时,推荐的方式为定义使用

<script id='templateName' type='text/x-jquery-tmpl'></script>

做为模板的包装器,但定义方式并不只有这一种,你可以使用

<divid="template"style="display: none;"><!-- markup --></div>

的方式来定义,但是官方文档中说,这种方法可能会产生浏览器无法解析的HTML,因此不推荐使用,不过我试了下,倒没有出什么意外:

<divid="container">
</div>
<divid="inline"style="display: none">
    <label>
        ${ID}</label>    
    <label>
        ${Name}</label><br/>
</div>
varusers = [{ ID:'think8848', Name:'Joseph Chan'}, { ID: 'aCloud', Name:'Mary Cheung'}];
$('#inline').tmpl(users).appendTo('#container');

效果:

编译缓存模板,在jQuery .tmpl()中,还可以将模板事先编译并缓存起来,然后在合适的时侯再使用,这对于一些数据嵌套是很有用的,如:

<tablecellspacing="0"cellpadding="3"border="1">
    <tbodyid="compileRows">
    </tbody>
</table>
<script id="compile1"type="text/x-jquery-tmpl">
    {{tmpl'cached'}}
    <tr><td>${ID}</td><td>${Name}</td></tr>
</script>
<script id="compile2"type="type/x-jquery-tmpl">
    <tr><td colspan="2">${Group}</td></tr>   
</script>
 
<script type="text/javascript">
    $(function() {
        vargroupUsers = [{ ID:'think8848', Name:'Joseph Chan', Group:'Administrators'}, { ID: 'aCloud', Name:'Mary Cheung', Group:'Users'}];
        $('#compile2').template('cached');
        $('#compile1').tmpl(groupUsers).appendTo('#compileRows');
    });
</script>

效果:

$.template()方法,将一段Html编译为模板,示例:

varmarkup ='<tr><td>${ID}</td><td>${Name}</td></tr>';
$.template('template', markup);
$.tmpl('template', users).appendTo('#templateRows');

这样就可以将markup中定义的模板应用于templateRows对象。

jQuery .tmpl()的标签,表达式,属性:

${}:从前面的例子来看,这个标签的作用很明显了,相当于是占位符,但是它还有另一种写法{{= field}}如:

<scriptid="myTemplate"type="text/x-jquery-tmpl">
    <tr><td>{{= ID}}</td><td>{{= Name}}</td></tr>
</script>

必须要注意的是,"="号后必须跟一个空格,不然是没有效果的。

另外,${}中还可以放表达式,这个牛x吧,如:

<tablecellspacing="0"cellpadding="3"border="1">
    <tbodyid="expressionRows">
    </tbody>
</table>
<script type="text/javascript">
    $(function() {
        varuserLangs = [{ ID:'think8848', Name:'Joseph Chan', Langs: ['Chinese','English'] }, { ID:'aCloud', Name:'Mary Cheung', Langs: ['Chinese','French']}];
        $('#expression').tmpl(userLangs).appendTo('#expressionRows');
    });
</script>

效果:

jQuery .tmpl()有两个比较有用的属性:$item$data:

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

<tablecellspacing="0"cellpadding="3"border="1">
    <tbodyid="propertyRows">
    </tbody>
</table>
<script id="property"type="text/x-jquery-tmpl">
    <tr><td>${ID}</td><td>${$data.Name}</td><td>${$item.getLangs('; ')}</td></tr> </script>
<script type="text/javascript">
    $(function() {
        varuserLangs = [{ ID:'think8848', Name:'Joseph Chan', Langs: ['Chinese','English'] }, { ID:'aCloud', Name:'Mary Cheung', Langs: ['Chinese','French']}];
        $('#property').tmpl(userLangs, {
            getLangs:function(separator) {
                returnthis.data.Langs.join(separator);
            }
        })
        .appendTo('#propertyRows');
    });
</script>

效果:

{{each}}这个标签一看就知道是做循环用的了,用法如下:

<ulid="eachList">
</ul>
<script id="each"type="text/x-jquery-tmpl">
      <li>ID: ${ID}; Name: ${Name};<br />Langs:<ul>{{each Langs}}<li>${$index + 1}: <label>${$value}. </label></li>{{/each}}<ul></li>
</script>
<script type="text/javascript">
    $(function() {
        varuserLangs = [{ ID:'think8848', Name:'Joseph Chan', Langs: ['Chinese','English'] }, { ID:'aCloud', Name:'Mary Cheung', Langs: ['Chinese','French']}];
        $('#each').tmpl(userLangs).appendTo('#eachList');
    });

效果:

{{each}}还有另一种写法:

<script id="each2"type="text/x-jquery-tmpl">
      <li>ID: ${ID}; Name: ${Name};<br />Langs:<ul><strong>{{each(i,lang) Langs}}<li>${i + 1}: <label>${lang}. </label></li>{{/each}}</strong></ul></li>
</script>

作用和前一种是一样的。

{{if}}和{{else}},这两个标签应该一看就知道作用了,直接上示例:

<script id="ifelse"type="text/x-jquery-tmpl">
      <tr><td>${ID}</td><td>${Name}</td><td>{{ifLangs.length > 1}}${Langs.join('; ')}{{else}}${Langs}{{/if}}</td></tr>
</script>

如果Langs数组元素超过1个,则用'; '连接起来,否则就直接显示Langs,效果:

{{html}},直接将对象属性值作为HTML代码替换占位符:

<script id="html"type="text/x-jquery-tmpl">
      <tr><td>${ID}</td><td>${Name}</td><td>{{html Ctrl}}</td></tr>
</script>
<script type="text/javascript">
    $(function() {
        varctrls = [{ ID:'think8848', Name:'Joseph Chan', Ctrl:'<input type="button" value="Demo" />'}, { ID: 'aCloud', Name:'Mary Cheung', Ctrl:'<input type="text" value="Demo" />'}];
        $('#html').tmpl(ctrls).appendTo('#htmlRows');
    });
</script>

效果:

{{tmpl}},前面已经提过该标签了,这里再给一个使用参数的例子:

<script id="tmpl1"type="text/x-jquery-tmpl">
    <tr><td>${ID}</td><td>${Name}</td><td> {{tmpl($data)'#tmpl2'}}</td></tr>      
</script>
<script id="tmpl2"type="type/x-jquery-tmpl">
    {{each Langs}}${$value}  {{/each}}  
</script>
<script type="text/javascript">
    $(function() {
        varuserLangs = [{ ID:'think8848', Name:'Joseph Chan', Langs: ['Chinese','English'] }, { ID:'aCloud', Name:'Mary Cheung', Langs: ['Chinese','French']}];
        $('#tmpl1').tmpl(userLangs).appendTo('#tmplRows');
    });
</script>

效果:

{{wrap}},包装器,这回不需要指定对哪一个元素使用模板了,直接生成模板的包装器,示例:

<divid="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>

效果:

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

$('tbody').delegate('tr','click',function() {
    varitem = $.tmplItem(this);
    alert(item.data.Name);
});

效果:

至此,官方的API中介绍的内容就完了,我的E文水平不高,对于某些细节难免理解不周,如有谬误之处,敬请指正,谢谢。

源代码下载

 https://github.com/jquery/jquery-tmpl

原创粉丝点击