翻译 jquery
JQuery.tmpl ( template, [data ,options] )git
* template : HTML 或 text 组成的 template;github
* data :将要渲染的数据,能够是 Javascript 中任意的一个数据类型,包括 object 或 array;ajax
* options :一个可选的用户自定义 key-value 键值对,扩展了 ‘tmplItem’ 的数据结构,并在 template 的渲染过程也可使用。json
返回:Jquery数组
Jquery Templates 插件的下载地址 是:https://github.com/BorisMoore/jquery-tmpl缓存
JQuery.tmpl() 方法能够和'.appendTo', '.prependTo','insertAfter' 及 '.insertBefore' 方法一块儿组成链式调用。以下例所示:数据结构
$.tmpl( "<li>${Name}</li>", { "Name" : "John Doe" }).appendTo( "#target" );
参数 template 的类型能够是如下任意一种形式:app
若 data 是一个数组,template 在渲染的过程当中会迭代数组中的每个 item, 若 data 是一个对象类型或为空,null, 则只会有一个template成员会被渲染。
ide
函数的返回值是一个 JQuery 包装的数组集合,集合里面包含了已经渲染成功的 template items. 若是这个 template 只包含了一个顶级成员,则数组中的全部成员只会有一个 element 与之对应。
若想把渲染好的 template items 插入到 HTML DOM 中,该函数返回的 Jquery 集合不能够直接的插入的 DOM 元素中,而是须要 '.appendTo', '.prependTo','insertAfter' 或 '.insertBefore' 方法一块儿进行链式调用。
Example 1 —— 本地数据
template 使用的是字符串形式。
var movies = [ { Name: "The Red Violin", ReleaseYear: "1998" }, { Name: "Eyes Wide Shut", ReleaseYear: "1999" }, { Name: "The Inheritance", ReleaseYear: "1976" } ]; var markup = "<li><b>${Name}</b> (${ReleaseYear})</li>"; // Compile the markup as a named template $.template( "movieTemplate", markup ); // Render the template with the movies data and insert // the rendered HTML under the "movieList" element $.tmpl( "movieTemplate", movies ).appendTo( "#movieList" );
Example 2 ——远端数据
var markup = "<li><b>${Name}</b> (${ReleaseYear})</li>"; // Compile the markup as a named template $.template( "movieTemplate", markup ); $.ajax({ dataType: "jsonp", url: moviesServiceUrl, jsonp: "$callback", success: showMovies }); // Within the callback, use .tmpl() to render the data. function showMovies( data ) { // Render the template with the "movies" data and insert // the rendered HTML under the 'movieList' element $.tmpl( "movieTemplate", data ) .appendTo( "#movieList" ); }
Options ——可扩展参数
Template 中的 每一个 item 都是和 'tmplItem' 相关联的,可使用 JQuery.tmplItem() 和 .tmplItem() 方法获得,或者可使用 ‘$item’ 方式。
JQuery.tmpl() 的 options 参数 中任何 fields 或 匿名函数都会自动扩展 'tmplItem' 数据结构,能够以下面这种方法使用:
var markup = "<li>Some content: ${$item.myMethod()}.<br/>" + " More content: ${$item.myValue}.</li>"; // Compile the markup as a named template $.template( "movieTemplate", markup ); // Render the template with the movies data $.tmpl( "movieTemplate", movies, { myValue: "somevalue", myMethod: function() { return "something"; } } ).appendTo( "#movieList" );
Template 的缓存机制
当一个 template 渲染成功以后,markup 会被首次转变成一个 compiled-template 方法。每调用一次“$.tmpl( markup , myData ).appendTo( "#target" )” 这个方法,template 都会被从新编译。若是一个相同的 template 须要被不一样的数据渲染屡次,此时就应该将这个已编译的 template 缓存起来。当使用一个 string 做为一个markup 来缓存 template 时,咱们可使用 '$.template( name, markup )' 这个方法来建立一个已申明的template, 以便重复使用。