PrototypeTemplate object learning _ prototype

Source: Internet
Author: User
The Template object here is actually a tool for formatting strings, just like the String. format method in java. This object provides only one evaluate method. The Code is as follows:


Var Template = Class. create ({
// Initialization Method
Initialize: function (template, pattern ){
This. template = template. toString ();
This. pattern = pattern | Template. Pattern;
},

// The formatting method. For java, it is actually better to call format :)
Evaluate: function (object ){
// Check whether the toTemplateReplacements method is defined. If yes, call
// In the entire Prototype framework, only the Hash object defines this method.
If (object & Object. isFunction (object. toTemplateReplacements ))
Object = object. toTemplateReplacements ();

// Here gsub is the method in the String object, which can be simply considered as replacing all parts of the String that match pattern.
Return this. template. gsub (this. pattern, function (match ){
// Match [0] is the entire string that matches Template. Pattern.
// Match [1] is a character that matches the character before the string.
// Match [2] is the part that matches the expression $ {var }.
// Match [3] is the 'var' part of the '# {var}' expression

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

// Obtain the first character of the matching expression
Var before = match [1] | '';
// If the previous string is '\', the matching expression is directly returned without replacement.
If (before = '\') return match [2];

Var ctx = object, expr = match [3];
// This regular expression seems to be checking whether var is a valid name. Why is it not understood?
Var pattern =/^ ([^. [] + | \[((? :.*? [^ \])?) \]) (\. | \ [| $ )/;
Match = pattern.exe c (expr );
// If var does not meet the requirements, the first character is directly returned.
If (match = null) return before;
// Replace the '# {var}' expression one by one
While (match! = Null ){
// What does this check mean?
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.exe c (expr );
}
// Return the replaced result, '# {var}' => 'value'
Return before + String. interpret (ctx );
});
}
});
// The default template matches the regular expression, such as # {var}. It is similar to the EL expression in JSP.
Template. Pattern =/(^ |. | \ r | \ n )(#\{(.*?) \})/;


The above basically explains the evaluate Method again, some places do not understand, those regular expressions are too difficult to understand... Who knows?

The following is an example:

The Code is as follows:


Var myTemplate = new Template ('the TV show # {title} was created by # {author }.');

Var show = {title: 'The Sons s', author: 'Matt groening', network: 'fox '};

MyTemplate. evaluate (show );
//-> The TV show The Simpsons was created by Matt Groening.


The Code is as follows:


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.


The Code is as follows:


// Custom matching mode
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




The Code is as follows:


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 # {}.');

[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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.