// 简单模板 function nano(template, data) { return template.replace(/\{([\w\.]*)\}/g, function(str, key) { var keys = key.split("."), v = data[keys.shift()]; for (var i = 0, l = keys.length; i < l; i++) v = v[keys[i]]; return (typeof v !== "undefined" && v !== null) ? v : ""; }); }
Basic Usage
Assuming you have following JSON response:
data = {
user: {
login: "tomek",
first_name: "Thomas",
last_name: "Mazur",
account: {
status: "active",
expires_at: "2009-12-31"
}
}
}
you can make:
nano("<p>Hello {user.first_name} {user.last_name}! Your account is <strong>{user.account.status}</strong></p>", data)
and you get ready string:
<p>Hello Thomas Mazur! Your account is <strong>active</strong></p>
原文:http://www.cnblogs.com/luffya/p/5189100.html