SoFunction
Updated on 2025-04-10

Prototype Template Object Learning


var Template = ({
//Initialization method
initialize: function(template, pattern) {
= ();
= pattern || ;
},

//Format method, from the perspective of Java, it is actually better to call format :)
evaluate: function(object) {
//Check whether the toTemplateReplacements method is defined. If yes, call it
//In the entire Prototype framework, only the Hash object defines this method
if (object && ())
object = ();

//The gsub here is a method in the String object. It can be simply considered to replace all parts of the string that match pattern.
return (, function(match) {
//match[0] is the entire matching string
//match[1] is a character before matching the string
//match[2] is the part that matches the expression ${var}
//match[3] is the 'var' part of the '#{var}' expression

//If object is null, replace all ${var} expressions with ''
if (object == null) return (match[1] + '');

//Get the previous character of the matching expression
var before = match[1] || '';
//If the previous string is '\', the matching expression will be returned directly without replacement
if (before == '\\') return match[2];

var ctx = object, expr = match[3];
//This regular expression seems to be checking whether var is a legal name. I haven't understood the meaning of this regular expression for the time being?
var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
match = (expr);
//If var does not meet the requirements, it will directly return the previous character
if (match == null) return before;
//Replace the '#{var}' expression part one by one
while (match != null) {
//Don’t understand what the following check means?
var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
ctx = ctx[comp];
if (null == ctx || '' == match[3]) break;
expr = ('[' == match[3] ? match[1].length : match[0].length);
match = (expr);
}
//Return the result after replacement, '#{var}' ==> 'value'
return before + (ctx);
});
}
});
//The default template matches regular expressions, like #{var}, which is very similar to the EL expression in JSP
= /(^|.|\r|\n)(#\{(.*?)\})/;