现在的位置: 首页 > 综合 > 正文

jquery插件:$.nano

2013年06月10日 ⁄ 综合 ⁄ 共 688字 ⁄ 字号 评论关闭

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

/* Nano Templates (Tomasz Mazur, Jacek Becela) */
(function($){
  $.nano = function(template, data) {
    return template.replace(/\{([\w\.]*)\}/g, function (str, key) {
      var keys = 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}! Your account is <strong>{user.account.status}</strong></p>", data)

你将得到如下字符串:

<p>Hello Thomas! Your account is <strong>active</strong></p>

很简单吧!!

抱歉!评论已关闭.