3 * Copyright(c) 2006-2010 Sencha Inc.
5 * http://www.sencha.com/license
9 * @extends Ext.Template
10 * <p>A template class that supports advanced functionality like:<div class="mdetail-params"><ul>
11 * <li>Autofilling arrays using templates and sub-templates</li>
12 * <li>Conditional processing with basic comparison operators</li>
13 * <li>Basic math function support</li>
14 * <li>Execute arbitrary inline code with special built-in template variables</li>
15 * <li>Custom member functions</li>
16 * <li>Many special tags and built-in operators that aren't defined as part of
17 * the API, but are supported in the templates that can be created</li>
19 * <p>XTemplate provides the templating mechanism built into:<div class="mdetail-params"><ul>
20 * <li>{@link Ext.DataView}</li>
21 * <li>{@link Ext.ListView}</li>
22 * <li>{@link Ext.form.ComboBox}</li>
23 * <li>{@link Ext.grid.TemplateColumn}</li>
24 * <li>{@link Ext.grid.GroupingView}</li>
25 * <li>{@link Ext.menu.Item}</li>
26 * <li>{@link Ext.layout.MenuLayout}</li>
27 * <li>{@link Ext.ColorPalette}</li>
30 * <p>For example usage {@link #XTemplate see the constructor}.</p>
33 * The {@link Ext.Template#Template Ext.Template constructor} describes
34 * the acceptable parameters to pass to the constructor. The following
35 * examples demonstrate all of the supported features.</p>
37 * <div class="mdetail-params"><ul>
39 * <li><b><u>Sample Data</u></b>
40 * <div class="sub-desc">
41 * <p>This is the data object used for reference in each code example:</p>
45 title: 'Lead Developer',
46 company: 'Ext JS, LLC',
47 email: 'jack@extjs.com',
48 address: '4 Red Bulls Drive',
52 drinks: ['Red Bull', 'Coffee', 'Water'],
69 * <li><b><u>Auto filling of arrays</u></b>
70 * <div class="sub-desc">
71 * <p>The <b><tt>tpl</tt></b> tag and the <b><tt>for</tt></b> operator are used
72 * to process the provided data object:
74 * <li>If the value specified in <tt>for</tt> is an array, it will auto-fill,
75 * repeating the template block inside the <tt>tpl</tt> tag for each item in the
77 * <li>If <tt>for="."</tt> is specified, the data object provided is examined.</li>
78 * <li>While processing an array, the special variable <tt>{#}</tt>
79 * will provide the current array index + 1 (starts at 1, not 0).</li>
83 <tpl <b>for</b>=".">...</tpl> // loop through array at root node
84 <tpl <b>for</b>="foo">...</tpl> // loop through array at foo node
85 <tpl <b>for</b>="foo.bar">...</tpl> // loop through array at foo.bar node
87 * Using the sample data above:
89 var tpl = new Ext.XTemplate(
91 '<tpl <b>for</b>=".">', // process the data.kids node
92 '<p>{#}. {name}</p>', // use current array index to autonumber
95 tpl.overwrite(panel.body, data.kids); // pass the kids property of the data object
97 * <p>An example illustrating how the <b><tt>for</tt></b> property can be leveraged
98 * to access specified members of the provided data object to populate the template:</p>
100 var tpl = new Ext.XTemplate(
101 '<p>Name: {name}</p>',
102 '<p>Title: {title}</p>',
103 '<p>Company: {company}</p>',
105 '<tpl <b>for="kids"</b>>', // interrogate the kids property within the data
106 '<p>{name}</p>',
109 tpl.overwrite(panel.body, data); // pass the root node of the data object
111 * <p>Flat arrays that contain values (and not objects) can be auto-rendered
112 * using the special <b><tt>{.}</tt></b> variable inside a loop. This variable
113 * will represent the value of the array at the current index:</p>
115 var tpl = new Ext.XTemplate(
116 '<p>{name}\'s favorite beverages:</p>',
117 '<tpl for="drinks">',
118 '<div> - {.}</div>',
121 tpl.overwrite(panel.body, data);
123 * <p>When processing a sub-template, for example while looping through a child array,
124 * you can access the parent object's members via the <b><tt>parent</tt></b> object:</p>
126 var tpl = new Ext.XTemplate(
127 '<p>Name: {name}</p>',
129 '<tpl for="kids">',
130 '<tpl if="age > 1">',
131 '<p>{name}</p>',
132 '<p>Dad: {<b>parent</b>.name}</p>',
136 tpl.overwrite(panel.body, data);
142 * <li><b><u>Conditional processing with basic comparison operators</u></b>
143 * <div class="sub-desc">
144 * <p>The <b><tt>tpl</tt></b> tag and the <b><tt>if</tt></b> operator are used
145 * to provide conditional checks for deciding whether or not to render specific
146 * parts of the template. Notes:<div class="sub-desc"><ul>
147 * <li>Double quotes must be encoded if used within the conditional</li>
148 * <li>There is no <tt>else</tt> operator — if needed, two opposite
149 * <tt>if</tt> statements should be used.</li>
152 <tpl if="age > 1 && age < 10">Child</tpl>
153 <tpl if="age >= 10 && age < 18">Teenager</tpl>
154 <tpl <b>if</b>="this.isGirl(name)">...</tpl>
155 <tpl <b>if</b>="id==\'download\'">...</tpl>
156 <tpl <b>if</b>="needsIcon"><img src="{icon}" class="{iconCls}"/></tpl>
158 <tpl if="name == "Jack"">Hello</tpl>
159 // encode " if it is part of the condition, e.g.
160 <tpl if="name == &quot;Jack&quot;">Hello</tpl>
162 * Using the sample data above:
164 var tpl = new Ext.XTemplate(
165 '<p>Name: {name}</p>',
167 '<tpl for="kids">',
168 '<tpl if="age > 1">',
169 '<p>{name}</p>',
173 tpl.overwrite(panel.body, data);
179 * <li><b><u>Basic math support</u></b>
180 * <div class="sub-desc">
181 * <p>The following basic math operators may be applied directly on numeric
182 * data values:</p><pre>
187 var tpl = new Ext.XTemplate(
188 '<p>Name: {name}</p>',
190 '<tpl for="kids">',
191 '<tpl if="age &gt; 1">', // <-- Note that the > is encoded
192 '<p>{#}: {name}</p>', // <-- Auto-number each item
193 '<p>In 5 Years: {age+5}</p>', // <-- Basic math
194 '<p>Dad: {parent.name}</p>',
198 tpl.overwrite(panel.body, data);
204 * <li><b><u>Execute arbitrary inline code with special built-in template variables</u></b>
205 * <div class="sub-desc">
206 * <p>Anything between <code>{[ ... ]}</code> is considered code to be executed
207 * in the scope of the template. There are some special variables available in that code:
209 * <li><b><tt>values</tt></b>: The values in the current scope. If you are using
210 * scope changing sub-templates, you can change what <tt>values</tt> is.</li>
211 * <li><b><tt>parent</tt></b>: The scope (values) of the ancestor template.</li>
212 * <li><b><tt>xindex</tt></b>: If you are in a looping template, the index of the
213 * loop you are in (1-based).</li>
214 * <li><b><tt>xcount</tt></b>: If you are in a looping template, the total length
215 * of the array you are looping.</li>
216 * <li><b><tt>fm</tt></b>: An alias for <tt>Ext.util.Format</tt>.</li>
218 * This example demonstrates basic row striping using an inline code block and the
219 * <tt>xindex</tt> variable:</p>
221 var tpl = new Ext.XTemplate(
222 '<p>Name: {name}</p>',
223 '<p>Company: {[values.company.toUpperCase() + ", " + values.title]}</p>',
225 '<tpl for="kids">',
226 '<div class="{[xindex % 2 === 0 ? "even" : "odd"]}">',
231 tpl.overwrite(panel.body, data);
236 * <li><b><u>Template member functions</u></b>
237 * <div class="sub-desc">
238 * <p>One or more member functions can be specified in a configuration
239 * object passed into the XTemplate constructor for more complex processing:</p>
241 var tpl = new Ext.XTemplate(
242 '<p>Name: {name}</p>',
244 '<tpl for="kids">',
245 '<tpl if="this.isGirl(name)">',
246 '<p>Girl: {name} - {age}</p>',
248 // use opposite if statement to simulate 'else' processing:
249 '<tpl if="this.isGirl(name) == false">',
250 '<p>Boy: {name} - {age}</p>',
252 '<tpl if="this.isBaby(age)">',
253 '<p>{name} is a baby!</p>',
257 // XTemplate configuration:
259 disableFormats: true,
261 isGirl: function(name){
262 return name == 'Sara Grace';
264 isBaby: function(age){
269 tpl.overwrite(panel.body, data);
276 * @param {Mixed} config
278 Ext.XTemplate = function(){
279 Ext.XTemplate.superclass.constructor.apply(this, arguments);
283 re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
284 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
285 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
286 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
295 WITHVALUES = 'with(values){ ';
297 s = ['<tpl>', s, '</tpl>'].join('');
299 while((m = s.match(re))){
300 var m2 = m[0].match(nameRe),
301 m3 = m[0].match(ifRe),
302 m4 = m[0].match(execRe),
306 name = m2 && m2[1] ? m2[1] : '';
309 exp = m3 && m3[1] ? m3[1] : null;
311 fn = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + RETURN +(Ext.util.Format.htmlDecode(exp))+'; }');
315 exp = m4 && m4[1] ? m4[1] : null;
317 exec = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES +(Ext.util.Format.htmlDecode(exp))+'; }');
322 case '.': name = new Function(VALUES, PARENT, WITHVALUES + RETURN + VALUES + '; }'); break;
323 case '..': name = new Function(VALUES, PARENT, WITHVALUES + RETURN + PARENT + '; }'); break;
324 default: name = new Function(VALUES, PARENT, WITHVALUES + RETURN + name + '; }');
334 s = s.replace(m[0], '{xtpl'+ id + '}');
337 for(var i = tpls.length-1; i >= 0; --i){
338 me.compileTpl(tpls[i]);
340 me.master = tpls[tpls.length-1];
343 Ext.extend(Ext.XTemplate, Ext.Template, {
345 re : /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\\]\s?[\d\.\+\-\*\\\(\)]+)?\}/g,
347 codeRe : /\{\[((?:\\\]|.|\n)*?)\]\}/g,
350 applySubTemplate : function(id, values, parent, xindex, xcount){
356 if ((t.test && !t.test.call(me, values, parent, xindex, xcount)) ||
357 (t.exec && t.exec.call(me, values, parent, xindex, xcount))) {
360 vs = t.target ? t.target.call(me, values, parent) : values;
362 parent = t.target ? values : parent;
363 if(t.target && Ext.isArray(vs)){
364 for(var i = 0, len = vs.length; i < len; i++){
365 buf[buf.length] = t.compiled.call(me, vs[i], parent, i+1, len);
369 return t.compiled.call(me, vs, parent, xindex, xcount);
373 compileTpl : function(tpl){
374 var fm = Ext.util.Format,
375 useF = this.disableFormats !== true,
376 sep = Ext.isGecko ? "+" : ",",
379 function fn(m, name, format, args, math){
380 if(name.substr(0, 4) == 'xtpl'){
381 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent, xindex, xcount)'+sep+"'";
386 }else if(name === '#'){
388 }else if(name.indexOf('.') != -1){
391 v = "values['" + name + "']";
394 v = '(' + v + math + ')';
396 if (format && useF) {
397 args = args ? ',' + args : "";
398 if(format.substr(0, 5) != "this."){
399 format = "fm." + format + '(';
401 format = 'this.call("'+ format.substr(5) + '", ';
405 args= ''; format = "("+v+" === undefined ? '' : ";
407 return "'"+ sep + format + v + args + ")"+sep+"'";
410 function codeFn(m, code){
411 // Single quotes get escaped when the template is compiled, however we want to undo this when running code.
412 return "'" + sep + '(' + code.replace(/\\'/g, "'") + ')' + sep + "'";
415 // branched to use + in gecko and [].join() in others
417 body = "tpl.compiled = function(values, parent, xindex, xcount){ return '" +
418 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn) +
421 body = ["tpl.compiled = function(values, parent, xindex, xcount){ return ['"];
422 body.push(tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn));
423 body.push("'].join('');};");
424 body = body.join('');
431 * Returns an HTML fragment of this template with the specified values applied.
432 * @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'})
433 * @return {String} The HTML fragment
435 applyTemplate : function(values){
436 return this.master.compiled.call(this, values, {}, 1, 1);
440 * Compile the template to a function for optimized performance. Recommended if the template will be used frequently.
441 * @return {Function} The compiled function
443 compile : function(){return this;}
450 * @property disableFormats
460 * Alias for {@link #applyTemplate}
461 * Returns an HTML fragment of this template with the specified values applied.
462 * @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'})
463 * @return {String} The HTML fragment
464 * @member Ext.XTemplate
467 Ext.XTemplate.prototype.apply = Ext.XTemplate.prototype.applyTemplate;
470 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
471 * @param {String/HTMLElement} el A DOM element or its id
472 * @return {Ext.Template} The created template
475 Ext.XTemplate.from = function(el){
477 return new Ext.XTemplate(el.value || el.innerHTML);