之前很是头疼循环数据的渲染,搞一大堆的命名,一点点的赋值,很是麻烦,今天学习了一下jQuery插件tmpl,下面抛出一些使用方法,供以后参考:
官方网址:http://web.archive.org/web/20121014080309/http://api.jquery.com/jquery.tmpl/
github网址:https://github.com/jquery/jquery-tmpl http://jquery.github.com/jquery-tmpl/demos/step-by-step.html
下面重点介绍一下使用方法:
首先介绍一下 模板和数据,不用说这两个肯定是不可缺少的
模板有两种定义方法,下面给出具体code
1.
var markup = "<li>Some content: ${item}.<br/>" + " More content: ${myValue}.</li>"; $.template( "movieTemplate", markup );
<script id="movieTemplate" type="text/x-jquery-tmpl"> <li><b>${Name}</b> (${ReleaseYear})</li> </script>
这样就定义了两种模板,前一种写到script里边,后边一种写到html里边
数据用json
下面开始渲染模板
$( "#movieTemplate" ).tmpl( movies ).appendTo( "#movieList" );
$.tmpl( "movieTemplate", movies ).appendTo( "#movieList" );
注意:movies是json数据数组
var movies = [ { Name: "The Red Violin", ReleaseYear: "1998" }, { Name: "Eyes Wide Shut", ReleaseYear: "1999" }, { Name: "The Inheritance", ReleaseYear: "1976" } ];
下面给出一些更深层次的操作数据的方法
1.判断:
<script id="movieTemplate" type="text/x-jquery-tmpl"> <tr> <td>${Title}</td> <td> {{if Languages}} Alternative languages: <em>${Languages}</em>. {{else Subtitles}} Original language only... Subtitles in <em>${Subtitles}</em>. {{else}} Original version only, without subtitles. {{/if}} </td> </tr> </script>
var movies = [ { Title: "Meet Joe Black", Languages: [ { Name: "English" }, { Name: "French" } ] } ];
<script id="movieTemplate" type="text/x-jquery-tmpl"> <tr> <td>${Title}</td> <td>Languages: <em> {{each Languages}} ${$value.Name} {{/each}} </em> </td> </tr> </script>
3.在应用中有时候想给模板里边填充一部分html代码
<script id="movieTemplate" type="text/x-jquery-tmpl"> <tr> <td>${Title}</td> <td class="synopsis">{{html Synopsis}}</td> </tr> </script>
4.应用中有时候也需要对数据进行一下处理
var markup = "<li>Some content: ${$item.myMethod()}.<br/>" + " More content: ${$item.myValue}.</li>"; $.template( "movieTemplate", markup ); $.tmpl( "movieTemplate", movies, { myValue: "somevalue", myMethod: function() { return "something"; } } ).appendTo( "#movieList" );