Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

最简单的jQuery模板引擎 #13

Open
lovecn opened this issue Nov 30, 2014 · 0 comments
Open

最简单的jQuery模板引擎 #13

lovecn opened this issue Nov 30, 2014 · 0 comments

Comments

@lovecn
Copy link
Owner

lovecn commented Nov 30, 2014

最简单的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("

Hello {user.first_name} {user.last_name}! Your account is {user.account.status}

", data)
你将得到如下字符串:

Hello Thomas! Your account is active

很简单吧!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant