프런트엔드 [템플릿 엔진]

1299 단어
//  
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> 

좋은 웹페이지 즐겨찾기