最简单的jQuery模板引擎,仅九行代码,完美实现对JSON的解析。

/*NanoTemplates(TomaszMazur,JacekBecela)*/(function($){ $.nano=function(template,data){ returntemplate.replace(/\{([\w\.]*)\}/g,function(str,key){ varkeys=key.split("."),value=data[keys.shift()]; $.each(keys,function(){value=value[this];}); return(value===null||value===undefined)?"":value; }); }; })(jQuery);

源码地址:https://github.com/trix/nano

假如你有如下JSON数据:

data={ user:{ login:"tomek", first_name:"Thomas", last_name:"Mazur", account:{ status:"active", expires_at:"2009-12-31"} } }

你有如下的模板:

$.nano("<p>Hello{user.first_name}{user.last_name}!Youraccountis<strong>{user.account.status}</strong></p>",data)

你将得到如下字符串:

<p>HelloThomas!Youraccountis<strong>active</strong></p>