3 * Copyright(c) 2006-2009 Ext JS, LLC
5 * http://www.extjs.com/license
9 * @extends Ext.Template
10 * <p>A template class that supports advanced functionality like autofilling arrays, conditional processing with
11 * basic comparison operators, sub-templates, basic math function support, special built-in template variables,
12 * inline code execution and more. XTemplate also provides the templating mechanism built into {@link Ext.DataView}.</p>
13 * <p>XTemplate supports many special tags and built-in operators that aren't defined as part of the API, but are
14 * supported in the templates that can be created. The following examples demonstrate all of the supported features.
15 * This is the data object used for reference in each code example:</p>
19 title: 'Lead Developer',
20 company: 'Ext JS, LLC',
21 email: 'jack@extjs.com',
22 address: '4 Red Bulls Drive',
26 drinks: ['Red Bull', 'Coffee', 'Water'],
39 * <p><b>Auto filling of arrays</b><br/>The <tt>tpl</tt> tag and the <tt>for</tt> operator are used
40 * to process the provided data object. If <tt>for="."</tt> is specified, the data object provided
41 * is examined. If the variable in <tt>for</tt> is an array, it will auto-fill, repeating the template
42 * block inside the <tt>tpl</tt> tag for each item in the array:</p>
44 var tpl = new Ext.XTemplate(
47 '<p>{name}</p>',
50 tpl.overwrite(panel.body, data.kids); // pass the kids property of the data object
52 * <p><b>Scope switching</b><br/>The <tt>for</tt> property can be leveraged to access specified members
53 * of the provided data object to populate the template:</p>
55 var tpl = new Ext.XTemplate(
56 '<p>Name: {name}</p>',
57 '<p>Title: {title}</p>',
58 '<p>Company: {company}</p>',
60 '<tpl <b>for="kids"</b>>', // interrogate the kids property within the data
61 '<p>{name}</p>',
64 tpl.overwrite(panel.body, data);
66 * <p><b>Access to parent object from within sub-template scope</b><br/>When processing a sub-template, for example while
67 * looping through a child array, you can access the parent object's members via the <tt>parent</tt> object:</p>
69 var tpl = new Ext.XTemplate(
70 '<p>Name: {name}</p>',
72 '<tpl for="kids">',
73 '<tpl if="age &gt; 1">', // <-- Note that the > is encoded
74 '<p>{name}</p>',
75 '<p>Dad: {parent.name}</p>',
79 tpl.overwrite(panel.body, data);
81 * <p><b>Array item index and basic math support</b> <br/>While processing an array, the special variable <tt>{#}</tt>
82 * will provide the current array index + 1 (starts at 1, not 0). Templates also support the basic math operators
83 * + - * and / that can be applied directly on numeric data values:</p>
85 var tpl = new Ext.XTemplate(
86 '<p>Name: {name}</p>',
88 '<tpl for="kids">',
89 '<tpl if="age &gt; 1">', // <-- Note that the > is encoded
90 '<p>{#}: {name}</p>', // <-- Auto-number each item
91 '<p>In 5 Years: {age+5}</p>', // <-- Basic math
92 '<p>Dad: {parent.name}</p>',
96 tpl.overwrite(panel.body, data);
98 * <p><b>Auto-rendering of flat arrays</b> <br/>Flat arrays that contain values (and not objects) can be auto-rendered
99 * using the special <tt>{.}</tt> variable inside a loop. This variable will represent the value of
100 * the array at the current index:</p>
102 var tpl = new Ext.XTemplate(
103 '<p>{name}\'s favorite beverages:</p>',
104 '<tpl for="drinks">',
105 '<div> - {.}</div>',
108 tpl.overwrite(panel.body, data);
110 * <p><b>Basic conditional logic</b> <br/>Using the <tt>tpl</tt> tag and the <tt>if</tt>
111 * operator you can provide conditional checks for deciding whether or not to render specific parts of the template.
112 * Note that there is no <tt>else</tt> operator — if needed, you should use two opposite <tt>if</tt> statements.
113 * Properly-encoded attributes are required as seen in the following example:</p>
115 var tpl = new Ext.XTemplate(
116 '<p>Name: {name}</p>',
118 '<tpl for="kids">',
119 '<tpl if="age &gt; 1">', // <-- Note that the > is encoded
120 '<p>{name}</p>',
124 tpl.overwrite(panel.body, data);
126 * <p><b>Ability to execute arbitrary inline code</b> <br/>In an XTemplate, anything between {[ ... ]} is considered
127 * code to be executed in the scope of the template. There are some special variables available in that code:
129 * <li><b><tt>values</tt></b>: The values in the current scope. If you are using scope changing sub-templates, you
130 * can change what <tt>values</tt> is.</li>
131 * <li><b><tt>parent</tt></b>: The scope (values) of the ancestor template.</li>
132 * <li><b><tt>xindex</tt></b>: If you are in a looping template, the index of the loop you are in (1-based).</li>
133 * <li><b><tt>xcount</tt></b>: If you are in a looping template, the total length of the array you are looping.</li>
134 * <li><b><tt>fm</tt></b>: An alias for <tt>Ext.util.Format</tt>.</li>
136 * This example demonstrates basic row striping using an inline code block and the <tt>xindex</tt> variable:</p>
138 var tpl = new Ext.XTemplate(
139 '<p>Name: {name}</p>',
140 '<p>Company: {[values.company.toUpperCase() + ", " + values.title]}</p>',
142 '<tpl for="kids">',
143 '<div class="{[xindex % 2 === 0 ? "even" : "odd"]}">',
148 tpl.overwrite(panel.body, data);
150 * <p><b>Template member functions</b> <br/>One or more member functions can be defined directly on the config
151 * object passed into the XTemplate constructor for more complex processing:</p>
153 var tpl = new Ext.XTemplate(
154 '<p>Name: {name}</p>',
156 '<tpl for="kids">',
157 '<tpl if="this.isGirl(name)">',
158 '<p>Girl: {name} - {age}</p>',
160 '<tpl if="this.isGirl(name) == false">',
161 '<p>Boy: {name} - {age}</p>',
163 '<tpl if="this.isBaby(age)">',
164 '<p>{name} is a baby!</p>',
166 '</tpl></p>', {
167 isGirl: function(name){
168 return name == 'Sara Grace';
170 isBaby: function(age){
174 tpl.overwrite(panel.body, data);
177 * @param {String/Array/Object} parts The HTML fragment or an array of fragments to join(""), or multiple arguments
178 * to join("") that can also include a config object
180 Ext.XTemplate = function(){
181 Ext.XTemplate.superclass.constructor.apply(this, arguments);
185 re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
186 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
187 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
188 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
197 WITHVALUES = 'with(values){ ';
199 s = ['<tpl>', s, '</tpl>'].join('');
201 while((m = s.match(re))){
202 var m2 = m[0].match(nameRe),
203 m3 = m[0].match(ifRe),
204 m4 = m[0].match(execRe),
208 name = m2 && m2[1] ? m2[1] : '';
211 exp = m3 && m3[1] ? m3[1] : null;
213 fn = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + RETURN +(Ext.util.Format.htmlDecode(exp))+'; }');
217 exp = m4 && m4[1] ? m4[1] : null;
219 exec = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES +(Ext.util.Format.htmlDecode(exp))+'; }');
224 case '.': name = new Function(VALUES, PARENT, WITHVALUES + RETURN + VALUES + '; }'); break;
225 case '..': name = new Function(VALUES, PARENT, WITHVALUES + RETURN + PARENT + '; }'); break;
226 default: name = new Function(VALUES, PARENT, WITHVALUES + RETURN + name + '; }');
236 s = s.replace(m[0], '{xtpl'+ id + '}');
239 Ext.each(tpls, function(t) {
242 me.master = tpls[tpls.length-1];
245 Ext.extend(Ext.XTemplate, Ext.Template, {
247 re : /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\\]\s?[\d\.\+\-\*\\\(\)]+)?\}/g,
249 codeRe : /\{\[((?:\\\]|.|\n)*?)\]\}/g,
252 applySubTemplate : function(id, values, parent, xindex, xcount){
258 if ((t.test && !t.test.call(me, values, parent, xindex, xcount)) ||
259 (t.exec && t.exec.call(me, values, parent, xindex, xcount))) {
262 vs = t.target ? t.target.call(me, values, parent) : values;
264 parent = t.target ? values : parent;
265 if(t.target && Ext.isArray(vs)){
266 Ext.each(vs, function(v, i) {
267 buf[buf.length] = t.compiled.call(me, v, parent, i+1, len);
271 return t.compiled.call(me, vs, parent, xindex, xcount);
275 compileTpl : function(tpl){
276 var fm = Ext.util.Format,
277 useF = this.disableFormats !== true,
278 sep = Ext.isGecko ? "+" : ",",
281 function fn(m, name, format, args, math){
282 if(name.substr(0, 4) == 'xtpl'){
283 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent, xindex, xcount)'+sep+"'";
288 }else if(name === '#'){
290 }else if(name.indexOf('.') != -1){
293 v = "values['" + name + "']";
296 v = '(' + v + math + ')';
298 if (format && useF) {
299 args = args ? ',' + args : "";
300 if(format.substr(0, 5) != "this."){
301 format = "fm." + format + '(';
303 format = 'this.call("'+ format.substr(5) + '", ';
307 args= ''; format = "("+v+" === undefined ? '' : ";
309 return "'"+ sep + format + v + args + ")"+sep+"'";
312 function codeFn(m, code){
313 return "'"+ sep +'('+code+')'+sep+"'";
316 // branched to use + in gecko and [].join() in others
318 body = "tpl.compiled = function(values, parent, xindex, xcount){ return '" +
319 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn) +
322 body = ["tpl.compiled = function(values, parent, xindex, xcount){ return ['"];
323 body.push(tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn));
324 body.push("'].join('');};");
325 body = body.join('');
332 * Returns an HTML fragment of this template with the specified values applied.
333 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
334 * @return {String} The HTML fragment
336 applyTemplate : function(values){
337 return this.master.compiled.call(this, values, {}, 1, 1);
341 * Compile the template to a function for optimized performance. Recommended if the template will be used frequently.
342 * @return {Function} The compiled function
344 compile : function(){return this;}
351 * @property disableFormats
361 * Alias for {@link #applyTemplate}
362 * Returns an HTML fragment of this template with the specified values applied.
363 * @param {Object/Array} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
364 * @return {String} The HTML fragment
365 * @member Ext.XTemplate
368 Ext.XTemplate.prototype.apply = Ext.XTemplate.prototype.applyTemplate;
371 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
372 * @param {String/HTMLElement} el A DOM element or its id
373 * @return {Ext.Template} The created template
376 Ext.XTemplate.from = function(el){
378 return new Ext.XTemplate(el.value || el.innerHTML);