翻译
JQuery.tmpl ( template, [data ,options] )
* template : HTML 或 text 组成的 template;
* data :将要渲染的数据,可以是 Javascript 中任意的一个数据类型,包括 object 或 array;
* options :一个可选的用户自定义 key-value 键值对,扩展了 ‘tmplItem’ 的数据结构,并在 template 的渲染过程也可以使用。
返回: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 的类型可以是以下任意一种形式:
- 一个字符串,包含 markup
- 一个 HTML 元素(或是包装的一个元素的 JQuery 对象)
- 一个字符串对应了一个已定义的 template 的名称 (jQuery.template() and .template() )
- 一个 compiled-template 方法 (JQuery.template() 和 .template() )
若 data 是一个数组,template 在渲染的过程中会迭代数组中的每一个 item, 若 data 是一个对象类型或为空,null, 则只会有一个template成员会被渲染。
函数的返回值是一个 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, 以便重复使用。