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!