Print Shortlink

XTemplate in Ext JS 4

Ext JS 4 makes you construct the UI by writing JavaScript code. You have to write few lines of JavaScript code to construct even a simple textbox or a button. So developers always try to look for a way to squeeze in raw HTML code. Ext JS 4 provides an XTemplate class that can be used (or abused) for this purpose. Most of my assignments in ExtJS 4 or Sencha Touch, XTemplate lands up being a curiously discussed topic.

For the old timers, XTemplate will remind you of the XPath expressions that we use in XSL stylesheets to locate various parts of the XML document. Using XTemplate you can define a HTML UI template that can be applied to your data. The result can be rendered on to the screen.

In the code below, you have a collection of countries in JSON format. The XTemplate has a simple for-loop that will display the name and capital of each country in a paragraph tag. The template is applied to the countries data and displayed in a panel.

var countries = [
                   { name: 'India',capital:"New Delhi"},
		   { name : "USA",capital:"Washington"},
		   { name : "UK",capital:"London"}
		];
Ext.application({
		   launch : function(){
                        //XTemplate definition
			var tpl = new Ext.XTemplate(
				    '<h6>Countries</h6>',
				    '<tpl for=".">',       
				        '<p>{#}. {name}: <i>{capital}</i></p>',  
				    '</tpl>'
			);
			Ext.create("Ext.panel.Panel",{
					html : tpl.apply(countries), //apply XTemplate with the data
					renderTo : Ext.getBody()        
				});
			}
		});

The only problem working with XTemplate is it’s frustrating syntax, particularly when you have to use single quotes and double quotes using escape sequences inside the template syntax. You can write if-else, switch-case conditions, loops etc., in XTemplate. Also a number of developers fall madly in love with XTemplate and abuse it leading to maintenance and browser portability issues. You have it use it judiciously.

Leave a Reply