|
下面一段程序就是microtemplating engine.
复制代码 代码如下:
var _tmplCache = {}
this.parseTemplate = function(str, data) {
/// <summary>
/// Client side template parser that uses <#= #> and <# code #> 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.
/// </summary>
/// <param name="str" type="string">The text of the template to expand</param>
/// <param name="data" type="var">
/// Any data that is to be merged. Pass an object and
/// that object's properties are visible as variables.
/// </param>
/// <returns type="string" />
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("<#").join("');")
.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 "< # ERROR: " + err.htmlEncode() + " # >";
}
如何使用:
复制代码 代码如下:parseTemplate($("#ItemTemplate").html(),{ name: "rick", address: { street: "32 kaiea", city: "paia"} } );
上面程序所用的模板:
复制代码 代码如下:<script id="ItemTemplate" type="text/html"><div><div><#= name #></div><div><#= address.street #></div> </div></script>
如果想用循环:
复制代码 代码如下:$.each(dataarray,function(index,dataItem){
parseTemplate($("#ItemTemplate").html(), dataItem );
})
很简单很精巧吧?
JavaScript技术:JSON JQUERY模板实现说明,转载需保留来源!
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。