3 <title>The source code</title>
4 <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
5 <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
7 <body onload="prettyPrint();">
8 <pre class="prettyprint lang-js">/*!
10 * Copyright(c) 2006-2009 Ext JS, LLC
12 * http://www.extjs.com/license
14 <div id="cls-Ext.XTemplate"></div>/**
15 * @class Ext.XTemplate
16 * @extends Ext.Template
17 * <p>A template class that supports advanced functionality like:<div class="mdetail-params"><ul>
18 * <li>Autofilling arrays using templates and sub-templates</li>
19 * <li>Conditional processing with basic comparison operators</li>
20 * <li>Basic math function support</li>
21 * <li>Execute arbitrary inline code with special built-in template variables</li>
22 * <li>Custom member functions</li>
23 * <li>Many special tags and built-in operators that aren't defined as part of
24 * the API, but are supported in the templates that can be created</li>
26 * <p>XTemplate provides the templating mechanism built into:<div class="mdetail-params"><ul>
27 * <li>{@link Ext.DataView}</li>
28 * <li>{@link Ext.ListView}</li>
29 * <li>{@link Ext.form.ComboBox}</li>
30 * <li>{@link Ext.grid.TemplateColumn}</li>
31 * <li>{@link Ext.grid.GroupingView}</li>
32 * <li>{@link Ext.menu.Item}</li>
33 * <li>{@link Ext.layout.MenuLayout}</li>
34 * <li>{@link Ext.ColorPalette}</li>
37 * <p>For example usage {@link #XTemplate see the constructor}.</p>
40 * The {@link Ext.Template#Template Ext.Template constructor} describes
41 * the acceptable parameters to pass to the constructor. The following
42 * examples demonstrate all of the supported features.</p>
44 * <div class="mdetail-params"><ul>
46 * <li><b><u>Sample Data</u></b>
47 * <div class="sub-desc">
48 * <p>This is the data object used for reference in each code example:</p>
52 title: 'Lead Developer',
53 company: 'Ext JS, LLC',
54 email: 'jack@extjs.com',
55 address: '4 Red Bulls Drive',
59 drinks: ['Red Bull', 'Coffee', 'Water'],
76 * <li><b><u>Auto filling of arrays</u></b>
77 * <div class="sub-desc">
78 * <p>The <b><tt>tpl</tt></b> tag and the <b><tt>for</tt></b> operator are used
79 * to process the provided data object:
81 * <li>If the value specified in <tt>for</tt> is an array, it will auto-fill,
82 * repeating the template block inside the <tt>tpl</tt> tag for each item in the
84 * <li>If <tt>for="."</tt> is specified, the data object provided is examined.</li>
85 * <li>While processing an array, the special variable <tt>{#}</tt>
86 * will provide the current array index + 1 (starts at 1, not 0).</li>
90 <tpl <b>for</b>=".">...</tpl> // loop through array at root node
91 <tpl <b>for</b>="foo">...</tpl> // loop through array at foo node
92 <tpl <b>for</b>="foo.bar">...</tpl> // loop through array at foo.bar node
94 * Using the sample data above:
96 var tpl = new Ext.XTemplate(
98 '<tpl <b>for</b>=".">', // process the data.kids node
99 '<p>{#}. {name}</p>', // use current array index to autonumber
102 tpl.overwrite(panel.body, data.kids); // pass the kids property of the data object
104 * <p>An example illustrating how the <b><tt>for</tt></b> property can be leveraged
105 * to access specified members of the provided data object to populate the template:</p>
107 var tpl = new Ext.XTemplate(
108 '<p>Name: {name}</p>',
109 '<p>Title: {title}</p>',
110 '<p>Company: {company}</p>',
112 '<tpl <b>for="kids"</b>>', // interrogate the kids property within the data
113 '<p>{name}</p>',
116 tpl.overwrite(panel.body, data); // pass the root node of the data object
118 * <p>Flat arrays that contain values (and not objects) can be auto-rendered
119 * using the special <b><tt>{.}</tt></b> variable inside a loop. This variable
120 * will represent the value of the array at the current index:</p>
122 var tpl = new Ext.XTemplate(
123 '<p>{name}\'s favorite beverages:</p>',
124 '<tpl for="drinks">',
125 '<div> - {.}</div>',
128 tpl.overwrite(panel.body, data);
130 * <p>When processing a sub-template, for example while looping through a child array,
131 * you can access the parent object's members via the <b><tt>parent</tt></b> object:</p>
133 var tpl = new Ext.XTemplate(
134 '<p>Name: {name}</p>',
136 '<tpl for="kids">',
137 '<tpl if="age > 1">',
138 '<p>{name}</p>',
139 '<p>Dad: {<b>parent</b>.name}</p>',
143 tpl.overwrite(panel.body, data);
149 * <li><b><u>Conditional processing with basic comparison operators</u></b>
150 * <div class="sub-desc">
151 * <p>The <b><tt>tpl</tt></b> tag and the <b><tt>if</tt></b> operator are used
152 * to provide conditional checks for deciding whether or not to render specific
153 * parts of the template. Notes:<div class="sub-desc"><ul>
154 * <li>Double quotes must be encoded if used within the conditional</li>
155 * <li>There is no <tt>else</tt> operator — if needed, two opposite
156 * <tt>if</tt> statements should be used.</li>
159 <tpl if="age > 1 && age < 10">Child</tpl>
160 <tpl if="age >= 10 && age < 18">Teenager</tpl>
161 <tpl <b>if</b>="this.isGirl(name)">...</tpl>
162 <tpl <b>if</b>="id==\'download\'">...</tpl>
163 <tpl <b>if</b>="needsIcon"><img src="{icon}" class="{iconCls}"/></tpl>
165 <tpl if="name == "Jack"">Hello</tpl>
166 // encode " if it is part of the condition, e.g.
167 <tpl if="name == &quot;Jack&quot;">Hello</tpl>
169 * Using the sample data above:
171 var tpl = new Ext.XTemplate(
172 '<p>Name: {name}</p>',
174 '<tpl for="kids">',
175 '<tpl if="age > 1">',
176 '<p>{name}</p>',
180 tpl.overwrite(panel.body, data);
186 * <li><b><u>Basic math support</u></b>
187 * <div class="sub-desc">
188 * <p>The following basic math operators may be applied directly on numeric
189 * data values:</p><pre>
194 var tpl = new Ext.XTemplate(
195 '<p>Name: {name}</p>',
197 '<tpl for="kids">',
198 '<tpl if="age &gt; 1">', // <-- Note that the > is encoded
199 '<p>{#}: {name}</p>', // <-- Auto-number each item
200 '<p>In 5 Years: {age+5}</p>', // <-- Basic math
201 '<p>Dad: {parent.name}</p>',
205 tpl.overwrite(panel.body, data);
211 * <li><b><u>Execute arbitrary inline code with special built-in template variables</u></b>
212 * <div class="sub-desc">
213 * <p>Anything between <code>{[ ... ]}</code> is considered code to be executed
214 * in the scope of the template. There are some special variables available in that code:
216 * <li><b><tt>values</tt></b>: The values in the current scope. If you are using
217 * scope changing sub-templates, you can change what <tt>values</tt> is.</li>
218 * <li><b><tt>parent</tt></b>: The scope (values) of the ancestor template.</li>
219 * <li><b><tt>xindex</tt></b>: If you are in a looping template, the index of the
220 * loop you are in (1-based).</li>
221 * <li><b><tt>xcount</tt></b>: If you are in a looping template, the total length
222 * of the array you are looping.</li>
223 * <li><b><tt>fm</tt></b>: An alias for <tt>Ext.util.Format</tt>.</li>
225 * This example demonstrates basic row striping using an inline code block and the
226 * <tt>xindex</tt> variable:</p>
228 var tpl = new Ext.XTemplate(
229 '<p>Name: {name}</p>',
230 '<p>Company: {[values.company.toUpperCase() + ", " + values.title]}</p>',
232 '<tpl for="kids">',
233 '<div class="{[xindex % 2 === 0 ? "even" : "odd"]}">',
238 tpl.overwrite(panel.body, data);
243 * <li><b><u>Template member functions</u></b>
244 * <div class="sub-desc">
245 * <p>One or more member functions can be specified in a configuration
246 * object passed into the XTemplate constructor for more complex processing:</p>
248 var tpl = new Ext.XTemplate(
249 '<p>Name: {name}</p>',
251 '<tpl for="kids">',
252 '<tpl if="this.isGirl(name)">',
253 '<p>Girl: {name} - {age}</p>',
255 // use opposite if statement to simulate 'else' processing:
256 '<tpl if="this.isGirl(name) == false">',
257 '<p>Boy: {name} - {age}</p>',
259 '<tpl if="this.isBaby(age)">',
260 '<p>{name} is a baby!</p>',
264 // XTemplate configuration:
266 disableFormats: true,
268 isGirl: function(name){
269 return name == 'Sara Grace';
271 isBaby: function(age){
276 tpl.overwrite(panel.body, data);
283 * @param {Mixed} config
285 Ext.XTemplate = function(){
286 Ext.XTemplate.superclass.constructor.apply(this, arguments);
290 re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
291 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
292 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
293 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
302 WITHVALUES = 'with(values){ ';
304 s = ['<tpl>', s, '</tpl>'].join('');
306 while((m = s.match(re))){
307 var m2 = m[0].match(nameRe),
308 m3 = m[0].match(ifRe),
309 m4 = m[0].match(execRe),
313 name = m2 && m2[1] ? m2[1] : '';
316 exp = m3 && m3[1] ? m3[1] : null;
318 fn = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + RETURN +(Ext.util.Format.htmlDecode(exp))+'; }');
322 exp = m4 && m4[1] ? m4[1] : null;
324 exec = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES +(Ext.util.Format.htmlDecode(exp))+'; }');
329 case '.': name = new Function(VALUES, PARENT, WITHVALUES + RETURN + VALUES + '; }'); break;
330 case '..': name = new Function(VALUES, PARENT, WITHVALUES + RETURN + PARENT + '; }'); break;
331 default: name = new Function(VALUES, PARENT, WITHVALUES + RETURN + name + '; }');
341 s = s.replace(m[0], '{xtpl'+ id + '}');
344 Ext.each(tpls, function(t) {
347 me.master = tpls[tpls.length-1];
350 Ext.extend(Ext.XTemplate, Ext.Template, {
352 re : /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\\]\s?[\d\.\+\-\*\\\(\)]+)?\}/g,
354 codeRe : /\{\[((?:\\\]|.|\n)*?)\]\}/g,
357 applySubTemplate : function(id, values, parent, xindex, xcount){
363 if ((t.test && !t.test.call(me, values, parent, xindex, xcount)) ||
364 (t.exec && t.exec.call(me, values, parent, xindex, xcount))) {
367 vs = t.target ? t.target.call(me, values, parent) : values;
369 parent = t.target ? values : parent;
370 if(t.target && Ext.isArray(vs)){
371 Ext.each(vs, function(v, i) {
372 buf[buf.length] = t.compiled.call(me, v, parent, i+1, len);
376 return t.compiled.call(me, vs, parent, xindex, xcount);
380 compileTpl : function(tpl){
381 var fm = Ext.util.Format,
382 useF = this.disableFormats !== true,
383 sep = Ext.isGecko ? "+" : ",",
386 function fn(m, name, format, args, math){
387 if(name.substr(0, 4) == 'xtpl'){
388 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent, xindex, xcount)'+sep+"'";
393 }else if(name === '#'){
395 }else if(name.indexOf('.') != -1){
398 v = "values['" + name + "']";
401 v = '(' + v + math + ')';
403 if (format && useF) {
404 args = args ? ',' + args : "";
405 if(format.substr(0, 5) != "this."){
406 format = "fm." + format + '(';
408 format = 'this.call("'+ format.substr(5) + '", ';
412 args= ''; format = "("+v+" === undefined ? '' : ";
414 return "'"+ sep + format + v + args + ")"+sep+"'";
417 function codeFn(m, code){
418 // Single quotes get escaped when the template is compiled, however we want to undo this when running code.
419 return "'" + sep + '(' + code.replace(/\\'/g, "'") + ')' + sep + "'";
422 // branched to use + in gecko and [].join() in others
424 body = "tpl.compiled = function(values, parent, xindex, xcount){ return '" +
425 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn) +
428 body = ["tpl.compiled = function(values, parent, xindex, xcount){ return ['"];
429 body.push(tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn));
430 body.push("'].join('');};");
431 body = body.join('');
437 <div id="method-Ext.XTemplate-applyTemplate"></div>/**
438 * Returns an HTML fragment of this template with the specified values applied.
439 * @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'})
440 * @return {String} The HTML fragment
442 applyTemplate : function(values){
443 return this.master.compiled.call(this, values, {}, 1, 1);
446 <div id="method-Ext.XTemplate-compile"></div>/**
447 * Compile the template to a function for optimized performance. Recommended if the template will be used frequently.
448 * @return {Function} The compiled function
450 compile : function(){return this;}
452 <div id="prop-Ext.XTemplate-re"></div>/**
456 <div id="prop-Ext.XTemplate-disableFormats"></div>/**
457 * @property disableFormats
460 <div id="method-Ext.XTemplate-set"></div>/**
466 <div id="method-Ext.XTemplate-apply"></div>/**
467 * Alias for {@link #applyTemplate}
468 * Returns an HTML fragment of this template with the specified values applied.
469 * @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'})
470 * @return {String} The HTML fragment
471 * @member Ext.XTemplate
474 Ext.XTemplate.prototype.apply = Ext.XTemplate.prototype.applyTemplate;
476 <div id="method-Ext.XTemplate-XTemplate.from"></div>/**
477 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
478 * @param {String/HTMLElement} el A DOM element or its id
479 * @return {Ext.Template} The created template
482 Ext.XTemplate.from = function(el){
484 return new Ext.XTemplate(el.value || el.innerHTML);