3 * @extends Ext.Template
4 * <p>A template class that supports advanced functionality like:<div class="mdetail-params"><ul>
5 * <li>Autofilling arrays using templates and sub-templates</li>
6 * <li>Conditional processing with basic comparison operators</li>
7 * <li>Basic math function support</li>
8 * <li>Execute arbitrary inline code with special built-in template variables</li>
9 * <li>Custom member functions</li>
10 * <li>Many special tags and built-in operators that aren't defined as part of
11 * the API, but are supported in the templates that can be created</li>
13 * <p>XTemplate provides the templating mechanism built into:<div class="mdetail-params"><ul>
14 * <li>{@link Ext.view.View}</li>
17 * <p>For example usage {@link #XTemplate see the constructor}.</p>
20 * The {@link Ext.Template#Template Ext.Template constructor} describes
21 * the acceptable parameters to pass to the constructor. The following
22 * examples demonstrate all of the supported features.</p>
24 * <div class="mdetail-params"><ul>
26 * <li><b><u>Sample Data</u></b>
27 * <div class="sub-desc">
28 * <p>This is the data object used for reference in each code example:</p>
32 title: 'Lead Developer',
33 company: 'Sencha Inc.',
34 email: 'tommy@sencha.com',
35 address: '5 Cups Drive',
39 drinks: ['Coffee', 'Soda', 'Water'],
56 * <li><b><u>Auto filling of arrays</u></b>
57 * <div class="sub-desc">
58 * <p>The <b><tt>tpl</tt></b> tag and the <b><tt>for</tt></b> operator are used
59 * to process the provided data object:
61 * <li>If the value specified in <tt>for</tt> is an array, it will auto-fill,
62 * repeating the template block inside the <tt>tpl</tt> tag for each item in the
64 * <li>If <tt>for="."</tt> is specified, the data object provided is examined.</li>
65 * <li>While processing an array, the special variable <tt>{#}</tt>
66 * will provide the current array index + 1 (starts at 1, not 0).</li>
70 <tpl <b>for</b>=".">...</tpl> // loop through array at root node
71 <tpl <b>for</b>="foo">...</tpl> // loop through array at foo node
72 <tpl <b>for</b>="foo.bar">...</tpl> // loop through array at foo.bar node
74 * Using the sample data above:
76 var tpl = new Ext.XTemplate(
78 '<tpl <b>for</b>=".">', // process the data.kids node
79 '<p>{#}. {name}</p>', // use current array index to autonumber
82 tpl.overwrite(panel.body, data.kids); // pass the kids property of the data object
84 * <p>An example illustrating how the <b><tt>for</tt></b> property can be leveraged
85 * to access specified members of the provided data object to populate the template:</p>
87 var tpl = new Ext.XTemplate(
88 '<p>Name: {name}</p>',
89 '<p>Title: {title}</p>',
90 '<p>Company: {company}</p>',
92 '<tpl <b>for="kids"</b>>', // interrogate the kids property within the data
93 '<p>{name}</p>',
96 tpl.overwrite(panel.body, data); // pass the root node of the data object
98 * <p>Flat arrays that contain values (and not objects) can be auto-rendered
99 * using the special <b><tt>{.}</tt></b> variable inside a loop. This variable
100 * will represent the value of 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>When processing a sub-template, for example while looping through a child array,
111 * you can access the parent object's members via the <b><tt>parent</tt></b> object:</p>
113 var tpl = new Ext.XTemplate(
114 '<p>Name: {name}</p>',
116 '<tpl for="kids">',
117 '<tpl if="age &gt; 1">',
118 '<p>{name}</p>',
119 '<p>Dad: {<b>parent</b>.name}</p>',
123 tpl.overwrite(panel.body, data);
129 * <li><b><u>Conditional processing with basic comparison operators</u></b>
130 * <div class="sub-desc">
131 * <p>The <b><tt>tpl</tt></b> tag and the <b><tt>if</tt></b> operator are used
132 * to provide conditional checks for deciding whether or not to render specific
133 * parts of the template. Notes:<div class="sub-desc"><ul>
134 * <li>Double quotes must be encoded if used within the conditional</li>
135 * <li>There is no <tt>else</tt> operator — if needed, two opposite
136 * <tt>if</tt> statements should be used.</li>
139 <tpl if="age > 1 && age < 10">Child</tpl>
140 <tpl if="age >= 10 && age < 18">Teenager</tpl>
141 <tpl <b>if</b>="this.isGirl(name)">...</tpl>
142 <tpl <b>if</b>="id==\'download\'">...</tpl>
143 <tpl <b>if</b>="needsIcon"><img src="{icon}" class="{iconCls}"/></tpl>
145 <tpl if="name == "Tommy"">Hello</tpl>
146 // encode " if it is part of the condition, e.g.
147 <tpl if="name == &quot;Tommy&quot;">Hello</tpl>
149 * Using the sample data above:
151 var tpl = new Ext.XTemplate(
152 '<p>Name: {name}</p>',
154 '<tpl for="kids">',
155 '<tpl if="age &gt; 1">',
156 '<p>{name}</p>',
160 tpl.overwrite(panel.body, data);
166 * <li><b><u>Basic math support</u></b>
167 * <div class="sub-desc">
168 * <p>The following basic math operators may be applied directly on numeric
169 * data values:</p><pre>
174 var tpl = new Ext.XTemplate(
175 '<p>Name: {name}</p>',
177 '<tpl for="kids">',
178 '<tpl if="age &gt; 1">', // <-- Note that the > is encoded
179 '<p>{#}: {name}</p>', // <-- Auto-number each item
180 '<p>In 5 Years: {age+5}</p>', // <-- Basic math
181 '<p>Dad: {[parent.name]}</p>',
185 tpl.overwrite(panel.body, data);
191 * <li><b><u>Execute arbitrary inline code with special built-in template variables</u></b>
192 * <div class="sub-desc">
193 * <p>Anything between <code>{[ ... ]}</code> is considered code to be executed
194 * in the scope of the template. There are some special variables available in that code:
196 * <li><b><tt>values</tt></b>: The values in the current scope. If you are using
197 * scope changing sub-templates, you can change what <tt>values</tt> is.</li>
198 * <li><b><tt>parent</tt></b>: The scope (values) of the ancestor template.</li>
199 * <li><b><tt>xindex</tt></b>: If you are in a looping template, the index of the
200 * loop you are in (1-based).</li>
201 * <li><b><tt>xcount</tt></b>: If you are in a looping template, the total length
202 * of the array you are looping.</li>
204 * This example demonstrates basic row striping using an inline code block and the
205 * <tt>xindex</tt> variable:</p>
207 var tpl = new Ext.XTemplate(
208 '<p>Name: {name}</p>',
209 '<p>Company: {[values.company.toUpperCase() + ", " + values.title]}</p>',
211 '<tpl for="kids">',
212 '<div class="{[xindex % 2 === 0 ? "even" : "odd"]}">',
217 tpl.overwrite(panel.body, data);
222 * <li><b><u>Template member functions</u></b>
223 * <div class="sub-desc">
224 * <p>One or more member functions can be specified in a configuration
225 * object passed into the XTemplate constructor for more complex processing:</p>
227 var tpl = new Ext.XTemplate(
228 '<p>Name: {name}</p>',
230 '<tpl for="kids">',
231 '<tpl if="this.isGirl(name)">',
232 '<p>Girl: {name} - {age}</p>',
234 // use opposite if statement to simulate 'else' processing:
235 '<tpl if="this.isGirl(name) == false">',
236 '<p>Boy: {name} - {age}</p>',
238 '<tpl if="this.isBaby(age)">',
239 '<p>{name} is a baby!</p>',
243 // XTemplate configuration:
246 isGirl: function(name){
247 return name == 'Sara Grace';
249 isBaby: function(age){
254 tpl.overwrite(panel.body, data);
261 * @param {Mixed} config
263 Ext.XTemplate = function() {
264 Ext.XTemplate.superclass.constructor.apply(this, arguments);
268 re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
269 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
270 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
271 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
279 WITHVALUES = 'with(values){ ',
290 s = ['<tpl>', s, '</tpl>'].join('');
292 while ((m = s.match(re))) {
293 m2 = m[0].match(nameRe);
294 m3 = m[0].match(ifRe);
295 m4 = m[0].match(execRe);
299 name = m2 && m2[1] ? m2[1] : '';
302 exp = m3 && m3[1] ? m3[1] : null;
304 fn = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + 'try{' + RETURN + (Ext.util.Format.htmlDecode(exp)) + ';}catch(e){return;}}');
308 exp = m4 && m4[1] ? m4[1] : null;
310 exec = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + (Ext.util.Format.htmlDecode(exp)) + '; }');
316 name = new Function(VALUES, PARENT, WITHVALUES + RETURN + VALUES + '; }');
319 name = new Function(VALUES, PARENT, WITHVALUES + RETURN + PARENT + '; }');
322 name = new Function(VALUES, PARENT, WITHVALUES + RETURN + name + '; }');
332 s = s.replace(m[0], '{xtpl' + id + '}');
335 for (i = tpls.length - 1; i >= 0; --i) {
336 me.compileTpl(tpls[i]);
338 me.master = tpls[tpls.length - 1];
341 Ext.extend(Ext.XTemplate, Ext.Template, {
342 re: /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\/]\s?[\d\.\+\-\*\/\(\)]+)?\}/g,
345 * @cfg {RegExp} codeRe The regular expression used to match code variables (default: matches <tt>{[expression]}</tt>).
347 codeRe: /\{\[((?:\\\]|.|\n)*?)\]\}/g,
350 applySubTemplate: function(id, values, parent, xindex, xcount) {
357 if ((t.test && !t.test.call(me, values, parent, xindex, xcount)) ||
358 (t.exec && t.exec.call(me, values, parent, xindex, xcount))) {
361 vs = t.target ? t.target.call(me, values, parent) : values;
363 parent = t.target ? values: parent;
364 if (t.target && Ext.isArray(vs)) {
365 for (i = 0, len = vs.length; i < len; i++) {
366 buf[buf.length] = t.compiled.call(me, vs[i], parent, i + 1, len);
370 return t.compiled.call(me, vs, parent, xindex, xcount);
374 compileTpl: function(tpl) {
375 var fm = Ext.util.Format,
376 useF = this.disableFormats !== true,
379 function fn(m, name, format, args, math) {
381 // name is what is inside the {}
383 // Name begins with xtpl, use a Sub Template
384 if (name.substr(0, 4) == 'xtpl') {
385 return "',this.applySubTemplate(" + name.substr(4) + ", values, parent, xindex, xcount),'";
387 // name = "." - Just use the values object.
389 v = 'typeof values == "string" ? values : ""';
392 // name = "#" - Use the xindex
393 else if (name == '#') {
397 // name has a . in it - Use object literal notation, starting from values
398 else if (name.indexOf('.') != -1) {
402 // name is a property of values
404 v = "values['" + name + "']";
407 v = '(' + v + math + ')';
409 if (format && useF) {
410 args = args ? ',' + args: "";
411 if (format.substr(0, 5) != "this.") {
412 format = "fm." + format + '(';
415 format = 'this.call("' + format.substr(5) + '", ';
421 format = "(" + v + " === undefined ? '' : ";
423 return "'," + format + v + args + "),'";
426 function codeFn(m, code) {
427 // Single quotes get escaped when the template is compiled, however we want to undo this when running code.
428 return "',(" + code.replace(/\\'/g, "'") + "),'";
430 body = ["tpl.compiled = function(values, parent, xindex, xcount){return ['"];
431 body.push(tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn));
432 body.push("'].join('');};");
433 body = body.join('');
439 * Returns an HTML fragment of this template with the specified values applied.
440 * @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'})
441 * @return {String} The HTML fragment
443 applyTemplate: function(values) {
444 return this.master.compiled.call(this, values, {}, 1, 1);
448 * Compile the template to a function for optimized performance. Recommended if the template will be used frequently.
449 * @return {Function} The compiled function
451 compile: function() {
456 * Alias for {@link #applyTemplate}
457 * Returns an HTML fragment of this template with the specified values applied.
458 * @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'})
459 * @return {String} The HTML fragment
460 * @member Ext.XTemplate
463 Ext.XTemplate.prototype.apply = Ext.XTemplate.prototype.applyTemplate;
465 if (Ext.util == undefined) {