码迷,mamicode.com
首页 > 其他好文 > 详细

前端 【模板引擎】

时间:2016-02-14 16:46:02      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

// 简单模板
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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!