可是在客户端再现数据也是一个不小的问题,用javascript处理经常会遇到很繁琐的事.尤其大批量具有相同结构的数据,例如表格,处理方式不尽如意.如果能有一个模板控件,就像服务器端asp.net Gridview或者repeater一样的东西就好很多.最近看到一个非常优秀的解决方案,让我在使用方便的同时不得不为作者的精巧设计而作一番感叹.该解决方案用了区区二十几行代码,实现了别人要用几十甚至上百K的js库所做的工作.它就是John Resig 的 Microtemplating engine.大师Rick Strahl有一篇文章专门对此作了详细讲述(Client Templating with Jquery).我在这里把最核心部分提取出来以方便国人学习。
下面一段程序就是microtemplating engine.
var _tmplCache = {}
this.parseTemplate = function(str, data) {
///
/// Client side template parser that uses and expressions.
/// and # # code blocks for template expansion.
/// NOTE: chokes on single quotes in the document in some situations
/// use ’ for literals in text and avoid any single quote
/// attribute delimiters.
/// ///
The text of the template to expand
///
/// Any data that is to be merged. Pass an object and
/// that object's properties are visible as variables.
///
///
var err = "";
try {
var func = _tmplCache[str];
if (!func) {
var strFunc =
"var p=[],print=function(){p.push.apply(p,arguments);};" +
"with(obj){p.push('" +
str.replace(/[\r\t\n]/g, " ")
.replace(/'(?=[^#]*#>)/g, "\t")
.split("'").join("\\'")
.split("\t").join("'")
.replace(//g, "',$1,'")
.split(".split("#>").join("p.push('")
+ "');}return p.join('');";
//alert(strFunc);
func = new Function("obj", strFunc);
_tmplCache[str] = func;
}
return func(data);
} catch (e) { err = e.message; }
return "";
}
parseTemplate($("#ItemTemplate").html(),{ name: "rick", address: { street: "32 kaiea", city: "paia"} } );