Nov 28, 2008

Prototype Templating

Templates are used for formatting group of similar objects and to produce formatted output for these objects.
Prototype provides a Template class which has two methods:
* Template(): This is a constructor method which is used to create a template object and call evaluate() method to apply template.
* evaluate(): This method is used to apply a template to format an object.

There are three steps involved to create formatted output.
1.Create a template: This involves creating preformatted text. This text contains formatted content along with #{fieldName} values. These #{fieldName} values will be replaced by the actual values when evaluate() method will be called with actual values.
2. Defining actual values: This involves creating actual values in the form of Keys and Values. These Keys will be mapped in the template and will be replaced by the corresponding values.
3. Mapping Keys and replacing Values: This is the final step where evaluate() will be called and all the keys available in the formatted object will be replaced by the defined values.

Example1 :
Step 1:
Create a template.
var myTemplate = new Template('The \
TV show #{title} was directed by #{author}.');

Step 2:
Prepare our set of values which will be passed in the above object to have a formatted output.
var record1 = {title: 'Metrix', author:'Arun Pandey'};
var record2 = {title: 'Junoon', author:'Manusha'};
var record3 = {title: 'Red Moon', author:'Paul, John'};
var record4 = {title: 'Henai', author:'Robert'};
var records = [record1, record2, record3, record4 ];

Step 3:
Final step is filling up all the values in the template and producing final result as follows:
records.each( function(conv){
alert( "Formatted Output : " + myTemplate.evaluate(conv) );
});

1 comment:

Vijay said...

Hi Harish,

This is a great start. I am really happy that you have decided to start this blog as a way to learn as well as to spread knowledge. I hope a lot of folks will collaborate. I certainly intend to. Good Luck.

Rgds,
Vijay