Complete code:
$.fn.parseTemplate = function(data )
{
var str = (this).html();
var _tmplCache = {}
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(/[rtn]/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.toString() " # >";
}
Usage:
First declare this template
and then use
$(function(){
var json={"items":{"pm": {"key":"value","key1":"value1"},"pm1":"pmvalue"}};
var output=$('#template').parseTemplate(json);
$('#cc').html(output);
})
It’s that simple!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn