Template

模板可以根据一定的格式替换个还原,在绑定数据的时候非常有用,默认的基本格式是将"#{fieldName}"替换为Json中对应的值

// Template声明语法 new Template(template[, pattern])
var myTemplate = new Template('The TV show #{title} was created by #{author}.');

//"数据源"Json
var show = {title: 'The Simpsons', author: 'Matt Groening', network: 'FOX' };

//绑定 使用evaluate()方法 调用方法 objTemplate.evaluate(Json)
myTemplate.evaluate(show);
// -> The TV show The Simpsons was created by Matt Groening.


也可以是数组绑定

//多个Json绑定
var conversion1 = {from: 'meters', to: 'feet', factor: 3.28};
var conversion2 = {from: 'kilojoules', to: 'BTUs', factor: 0.9478};
var conversion3 = {from: 'megabytes', to: 'gigabytes', factor: 1024};

//the template
var templ = new Template('Multiply by #{factor} to convert from #{from} to #{to}.');

//调用Array的each()方法
[conversion1, conversion2, conversion3].each( function(conv){
templ.evaluate(conv); //使用evaluate()替换
});
// -> Multiply by 3.28 to convert from meters to feet.
// -> Multiply by 0.9478 to convert from kilojoules to BTUs.
// -> Multiply by 1024 to convert from megabytes to gigabytes.

如果不想替换#{fieldName},可以用'\'转意即可,但由于'\'在Javascript中本身需要转意,所以需要\\

var t = new Template('in #{lang} we also use the \\#{variable} syntax for templates.');
var data = {lang:'Ruby', variable: '(not used)'};
t.evaluate(data);
// -> in Ruby we also use the #{variable} syntax for templates. \\#{variable}不被替换

自定义语法,由于默认的是替换行似#{fileName},现在来实现asp.net中的<%= fieldName%>

var syntax = /(^|.|\r|\n)(\<%=\s*(\w+)\s*%\>)/; //形似 '<%= field %>' 的RegExp
var t = new Template('<div>Name: <b><%= name %></b>, Age: <b><%=age%></b></div>', syntax);
t.evaluate( {name: 'John Smith', age: 26} ); // -> <div>Name: <b>John Smith</b>, Age: <b>26</b></div>

evaluate()执行时的一些特殊情况

var hrefTemplate = new Template('/dir/showAll?lang=#{language}&categ=#{category}&lv=#{levels}');
var selection = {category: 'books' , language: 'en-US'};

hrefTemplate.evaluate(selection);
// -> '/dir/showAll?lang=en-US&categ=books&lv='

hrefTemplate.evaluate({language: 'jp', levels: 3, created: '10/12/2005'});
// -> '/dir/showAll?lang=jp&categ=&lv=3'

hrefTemplate.evaluate({});
// -> '/dir/showAll?lang=&categ=&lv='

hrefTemplate.evaluate(null);
// -> error !


Template的实现:是否记得String.gsub()方法,这个方法可以用正则表达式替换,所以Template的实现的核心就是调用这个方法

var Template = Class.create();
   Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;//默认的正则表达式
   Template.prototype = {
       initialize: function(template, pattern) {//构造函数
       this.template = template.toString();
       this.pattern = pattern || Template.Pattern;//默认的Pattern
},

evaluate: function(object) {
      return this.template.gsub(this.pattern, function(match) {
         var before = match[1];//match数组是所有的匹配处数组
         if (before == '\\') return match[2];//转意\\
         return before + String.interpret(object[match[3]]);//别忘了object是Json可以用Json["key"]访问
         });
      }
}