Extract the template class out of string.js and into its own file.
This commit is contained in:
parent
314e161c57
commit
616319377f
|
@ -230,37 +230,3 @@ Object.extend(String.prototype.escapeHTML, {
|
|||
|
||||
String.prototype.escapeHTML.div.appendChild(String.prototype.escapeHTML.text);
|
||||
|
||||
var Template = Class.create({
|
||||
initialize: function(template, pattern) {
|
||||
this.template = template.toString();
|
||||
this.pattern = pattern || Template.Pattern;
|
||||
},
|
||||
|
||||
evaluate: function(object) {
|
||||
if (Object.isFunction(object.toTemplateReplacements))
|
||||
object = object.toTemplateReplacements();
|
||||
|
||||
return this.template.gsub(this.pattern, function(match) {
|
||||
if (object == null) return '';
|
||||
|
||||
var before = match[1] || '';
|
||||
if (before == '\\') return match[2];
|
||||
|
||||
var ctx = object, expr = match[3];
|
||||
var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
|
||||
match = pattern.exec(expr);
|
||||
if (match == null) return before;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
return before + String.interpret(ctx);
|
||||
});
|
||||
}
|
||||
});
|
||||
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
|
||||
|
|
|
@ -0,0 +1,34 @@
|
|||
var Template = Class.create({
|
||||
initialize: function(template, pattern) {
|
||||
this.template = template.toString();
|
||||
this.pattern = pattern || Template.Pattern;
|
||||
},
|
||||
|
||||
evaluate: function(object) {
|
||||
if (Object.isFunction(object.toTemplateReplacements))
|
||||
object = object.toTemplateReplacements();
|
||||
|
||||
return this.template.gsub(this.pattern, function(match) {
|
||||
if (object == null) return '';
|
||||
|
||||
var before = match[1] || '';
|
||||
if (before == '\\') return match[2];
|
||||
|
||||
var ctx = object, expr = match[3];
|
||||
var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
|
||||
match = pattern.exec(expr);
|
||||
if (match == null) return before;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
return before + String.interpret(ctx);
|
||||
});
|
||||
}
|
||||
});
|
||||
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
|
Loading…
Reference in New Issue