代码如下:
var Template = Class.create({
//初始化方法
initialize: function(template, pattern) {
this.template = template.toString();
this.pattern = pattern || Template.Pattern;
},
//格式化方法,如果从java的角度来说,其实叫format更好 :)
evaluate: function(object) {
//检查是否定义了toTemplateReplacements方法,是的话调用
//整个的Prototype框架中,只有Hash对象定义了这个方法
if (object && Object.isFunction(object.toTemplateReplacements))
object = object.toTemplateReplacements();
//这里的gsub是String对象里面的方法,可以简单的认为就是替换字符串中所有匹配pattern的部分
return this.template.gsub(this.pattern, function(match) {
//match[0]是整个的匹配Template.Pattern的字符串
//match[1]是匹配字符串前面的一个字符
//match[2]是匹配${var}这个表达式的部分
//match[3]是'#{var}'表达式的'var'部分
//如果object为null,则把所有的${var}表达式替换成''
if (object == null) return (match[1] + '');
//取得匹配表达式前一个字符
var before = match[1] || '';
//如果前一个字符串为'\',则直接返回匹配的表达式,不进行替换
if (before == '\\') return match[2];
var ctx = object, expr = match[3];
//这个正则表达式好像就是检查var是否是合法的名称,暂时没看懂这个正则表达式的意义?
var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
match = pattern.exec(expr);
//如果var不符合要求,则直接返回前一个字符
if (match == null) return before;
//逐个替换'#{var}'表达式部分
while (match != null) {
//不懂下面这个检查什么意思?
var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
ctx = ctx[comp];
if (null == ctx || '' == match[3]) break;
expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
match = pattern.exec(expr);
}
//返回替换后的结果,'#{var}' ==> 'value'
return before + String.interpret(ctx);
});
}
});
//默认的模板匹配正则表达式,形如#{var},很像JSP中的EL表达式
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
上面基本上把evaluate方法讲了一遍,有些地方没怎么看明白,那些正则表达式太难懂了。。。谁知道的告诉我?
下面看一下示例:
代码如下:
var myTemplate = new Template('The TV show #{title} was created by #{author}.');
var show = {title: 'The Simpsons', author: 'Matt Groening', network: 'FOX' };
myTemplate.evaluate(show);
// -> The TV show The Simpsons was created by Matt Groening.
代码如下:
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.
代码如下:
//自定义匹配模式
var syntax = /(^|.|\r|\n)(\<%=\s*(\w+)\s*%\>)/;
//matches symbols like '<%= field %>'
var t = new Template('
Name: <%= name %>, Age: <%=age%>
', syntax);
t.evaluate( {name: 'John Smith', age: 26} );
// ->
Name: John Smith, Age: 26
代码如下:
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};
var templ = new Template('Multiply by #{factor} to convert from #{from} to #{to}.');
[conversion1, conversion2, conversion3].each( function(conv){ templ.evaluate(conv); });
// -> 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.