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 * The {@link Ext.Template} describes
18 * the acceptable parameters to pass to the constructor. The following
19 * examples demonstrate all of the supported features.</p>
21 * <div class="mdetail-params"><ul>
23 * <li><b><u>Sample Data</u></b>
24 * <div class="sub-desc">
25 * <p>This is the data object used for reference in each code example:</p>
29 title: 'Lead Developer',
30 company: 'Sencha Inc.',
31 email: 'tommy@sencha.com',
32 address: '5 Cups Drive',
36 drinks: ['Coffee', 'Soda', 'Water'],
53 * <li><b><u>Auto filling of arrays</u></b>
54 * <div class="sub-desc">
55 * <p>The <b><tt>tpl</tt></b> tag and the <b><tt>for</tt></b> operator are used
56 * to process the provided data object:
58 * <li>If the value specified in <tt>for</tt> is an array, it will auto-fill,
59 * repeating the template block inside the <tt>tpl</tt> tag for each item in the
61 * <li>If <tt>for="."</tt> is specified, the data object provided is examined.</li>
62 * <li>While processing an array, the special variable <tt>{#}</tt>
63 * will provide the current array index + 1 (starts at 1, not 0).</li>
67 <tpl <b>for</b>=".">...</tpl> // loop through array at root node
68 <tpl <b>for</b>="foo">...</tpl> // loop through array at foo node
69 <tpl <b>for</b>="foo.bar">...</tpl> // loop through array at foo.bar node
71 * Using the sample data above:
73 var tpl = new Ext.XTemplate(
75 '<tpl <b>for</b>=".">', // process the data.kids node
76 '<p>{#}. {name}</p>', // use current array index to autonumber
79 tpl.overwrite(panel.body, data.kids); // pass the kids property of the data object
81 * <p>An example illustrating how the <b><tt>for</tt></b> property can be leveraged
82 * to access specified members of the provided data object to populate the template:</p>
84 var tpl = new Ext.XTemplate(
85 '<p>Name: {name}</p>',
86 '<p>Title: {title}</p>',
87 '<p>Company: {company}</p>',
89 '<tpl <b>for="kids"</b>>', // interrogate the kids property within the data
90 '<p>{name}</p>',
93 tpl.overwrite(panel.body, data); // pass the root node of the data object
95 * <p>Flat arrays that contain values (and not objects) can be auto-rendered
96 * using the special <b><tt>{.}</tt></b> variable inside a loop. This variable
97 * will represent the value of the array at the current index:</p>
99 var tpl = new Ext.XTemplate(
100 '<p>{name}\'s favorite beverages:</p>',
101 '<tpl for="drinks">',
102 '<div> - {.}</div>',
105 tpl.overwrite(panel.body, data);
107 * <p>When processing a sub-template, for example while looping through a child array,
108 * you can access the parent object's members via the <b><tt>parent</tt></b> object:</p>
110 var tpl = new Ext.XTemplate(
111 '<p>Name: {name}</p>',
113 '<tpl for="kids">',
114 '<tpl if="age &gt; 1">',
115 '<p>{name}</p>',
116 '<p>Dad: {<b>parent</b>.name}</p>',
120 tpl.overwrite(panel.body, data);
126 * <li><b><u>Conditional processing with basic comparison operators</u></b>
127 * <div class="sub-desc">
128 * <p>The <b><tt>tpl</tt></b> tag and the <b><tt>if</tt></b> operator are used
129 * to provide conditional checks for deciding whether or not to render specific
130 * parts of the template. Notes:<div class="sub-desc"><ul>
131 * <li>Double quotes must be encoded if used within the conditional</li>
132 * <li>There is no <tt>else</tt> operator — if needed, two opposite
133 * <tt>if</tt> statements should be used.</li>
136 <tpl if="age > 1 && age < 10">Child</tpl>
137 <tpl if="age >= 10 && age < 18">Teenager</tpl>
138 <tpl <b>if</b>="this.isGirl(name)">...</tpl>
139 <tpl <b>if</b>="id==\'download\'">...</tpl>
140 <tpl <b>if</b>="needsIcon"><img src="{icon}" class="{iconCls}"/></tpl>
142 <tpl if="name == "Tommy"">Hello</tpl>
143 // encode " if it is part of the condition, e.g.
144 <tpl if="name == &quot;Tommy&quot;">Hello</tpl>
146 * Using the sample data above:
148 var tpl = new Ext.XTemplate(
149 '<p>Name: {name}</p>',
151 '<tpl for="kids">',
152 '<tpl if="age &gt; 1">',
153 '<p>{name}</p>',
157 tpl.overwrite(panel.body, data);
163 * <li><b><u>Basic math support</u></b>
164 * <div class="sub-desc">
165 * <p>The following basic math operators may be applied directly on numeric
166 * data values:</p><pre>
171 var tpl = new Ext.XTemplate(
172 '<p>Name: {name}</p>',
174 '<tpl for="kids">',
175 '<tpl if="age &gt; 1">', // <-- Note that the > is encoded
176 '<p>{#}: {name}</p>', // <-- Auto-number each item
177 '<p>In 5 Years: {age+5}</p>', // <-- Basic math
178 '<p>Dad: {parent.name}</p>',
182 tpl.overwrite(panel.body, data);
188 * <li><b><u>Execute arbitrary inline code with special built-in template variables</u></b>
189 * <div class="sub-desc">
190 * <p>Anything between <code>{[ ... ]}</code> is considered code to be executed
191 * in the scope of the template. There are some special variables available in that code:
193 * <li><b><tt>values</tt></b>: The values in the current scope. If you are using
194 * scope changing sub-templates, you can change what <tt>values</tt> is.</li>
195 * <li><b><tt>parent</tt></b>: The scope (values) of the ancestor template.</li>
196 * <li><b><tt>xindex</tt></b>: If you are in a looping template, the index of the
197 * loop you are in (1-based).</li>
198 * <li><b><tt>xcount</tt></b>: If you are in a looping template, the total length
199 * of the array you are looping.</li>
201 * This example demonstrates basic row striping using an inline code block and the
202 * <tt>xindex</tt> variable:</p>
204 var tpl = new Ext.XTemplate(
205 '<p>Name: {name}</p>',
206 '<p>Company: {[values.company.toUpperCase() + ", " + values.title]}</p>',
208 '<tpl for="kids">',
209 '<div class="{[xindex % 2 === 0 ? "even" : "odd"]}">',
214 tpl.overwrite(panel.body, data);
219 * <li><b><u>Template member functions</u></b>
220 * <div class="sub-desc">
221 * <p>One or more member functions can be specified in a configuration
222 * object passed into the XTemplate constructor for more complex processing:</p>
224 var tpl = new Ext.XTemplate(
225 '<p>Name: {name}</p>',
227 '<tpl for="kids">',
228 '<tpl if="this.isGirl(name)">',
229 '<p>Girl: {name} - {age}</p>',
231 // use opposite if statement to simulate 'else' processing:
232 '<tpl if="this.isGirl(name) == false">',
233 '<p>Boy: {name} - {age}</p>',
235 '<tpl if="this.isBaby(age)">',
236 '<p>{name} is a baby!</p>',
240 // XTemplate configuration:
243 isGirl: function(name){
244 return name == 'Sara Grace';
246 isBaby: function(age){
251 tpl.overwrite(panel.body, data);
258 * @param {Mixed} config
261 Ext.define('Ext.XTemplate', {
263 /* Begin Definitions */
265 extend: 'Ext.Template',
269 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
270 * @param {String/HTMLElement} el A DOM element or its id
271 * @return {Ext.Template} The created template
274 from: function(el, config) {
276 return new this(el.value || el.innerHTML, config || {});
280 /* End Definitions */
282 argsRe: /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
283 nameRe: /^<tpl\b[^>]*?for="(.*?)"/,
284 ifRe: /^<tpl\b[^>]*?if="(.*?)"/,
285 execRe: /^<tpl\b[^>]*?exec="(.*?)"/,
286 constructor: function() {
287 this.callParent(arguments);
302 WITHVALUES = 'with(values){ ',
303 m, matchName, matchIf, matchExec, exp, fn, exec, name, i;
305 html = ['<tpl>', html, '</tpl>'].join('');
307 while ((m = html.match(argsRe))) {
311 matchName = m[0].match(nameRe);
312 matchIf = m[0].match(ifRe);
313 matchExec = m[0].match(execRe);
315 exp = matchIf ? matchIf[1] : null;
317 fn = Ext.functionFactory(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + 'try{' + RETURN + Ext.String.htmlDecode(exp) + ';}catch(e){return;}}');
320 exp = matchExec ? matchExec[1] : null;
322 exec = Ext.functionFactory(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + Ext.String.htmlDecode(exp) + ';}');
325 name = matchName ? matchName[1] : null;
329 } else if (name === '..') {
332 name = Ext.functionFactory(VALUES, PARENT, 'try{' + WITHVALUES + RETURN + name + ';}}catch(e){return;}');
343 html = html.replace(m[0], '{xtpl' + id + '}');
347 for (i = tpls.length - 1; i >= 0; --i) {
348 me.compileTpl(tpls[i]);
350 me.master = tpls[tpls.length - 1];
355 applySubTemplate: function(id, values, parent, xindex, xcount) {
356 var me = this, t = me.tpls[id];
357 return t.compiled.call(me, values, parent, xindex, xcount);
360 * @cfg {RegExp} codeRe The regular expression used to match code variables (default: matches <tt>{[expression]}</tt>).
362 codeRe: /\{\[((?:\\\]|.|\n)*?)\]\}/g,
364 re: /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\/]\s?[\d\.\+\-\*\/\(\)]+)?\}/g,
367 compileTpl: function(tpl) {
368 var fm = Ext.util.Format,
370 useFormat = me.disableFormats !== true,
371 body, bodyReturn, evaluatedFn;
373 function fn(m, name, format, args, math) {
375 // name is what is inside the {}
376 // Name begins with xtpl, use a Sub Template
377 if (name.substr(0, 4) == 'xtpl') {
378 return "',this.applySubTemplate(" + name.substr(4) + ", values, parent, xindex, xcount),'";
380 // name = "." - Just use the values object.
382 // filter to not include arrays/objects/nulls
383 v = 'Ext.Array.indexOf(["string", "number", "boolean"], typeof values) > -1 || Ext.isDate(values) ? values : ""';
386 // name = "#" - Use the xindex
387 else if (name == '#') {
390 else if (name.substr(0, 7) == "parent.") {
393 // name has a . in it - Use object literal notation, starting from values
394 else if (name.indexOf('.') != -1) {
395 v = "values." + name;
398 // name is a property of values
400 v = "values['" + name + "']";
403 v = '(' + v + math + ')';
405 if (format && useFormat) {
406 args = args ? ',' + args : "";
407 if (format.substr(0, 5) != "this.") {
408 format = "fm." + format + '(';
411 format = 'this.' + format.substr(5) + '(';
416 format = "(" + v + " === undefined ? '' : ";
418 return "'," + format + v + args + "),'";
421 function codeFn(m, code) {
422 // Single quotes get escaped when the template is compiled, however we want to undo this when running code.
423 return "',(" + code.replace(me.compileARe, "'") + "),'";
426 bodyReturn = tpl.body.replace(me.compileBRe, '\\n').replace(me.compileCRe, "\\'").replace(me.re, fn).replace(me.codeRe, codeFn);
427 body = "evaluatedFn = function(values, parent, xindex, xcount){return ['" + bodyReturn + "'].join('');};";
430 tpl.compiled = function(values, parent, xindex, xcount) {
436 if (tpl.test && !tpl.test.call(me, values, parent, xindex, xcount)) {
440 vs = tpl.target ? tpl.target.call(me, values, parent) : values;
445 parent = tpl.target ? values : parent;
446 if (tpl.target && Ext.isArray(vs)) {
450 for (i = 0; i < length; i++) {
451 buffer[buffer.length] = evaluatedFn.call(me, vs[i], parent, i + 1, length);
452 tpl.exec.call(me, vs[i], parent, i + 1, length);
455 for (i = 0; i < length; i++) {
456 buffer[buffer.length] = evaluatedFn.call(me, vs[i], parent, i + 1, length);
459 return buffer.join('');
463 tpl.exec.call(me, vs, parent, xindex, xcount);
465 return evaluatedFn.call(me, vs, parent, xindex, xcount);
472 * Returns an HTML fragment of this template with the specified values applied.
473 * @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'})
474 * @return {String} The HTML fragment
476 applyTemplate: function(values) {
477 return this.master.compiled.call(this, values, {}, 1, 1);
481 * Compile the template to a function for optimized performance. Recommended if the template will be used frequently.
482 * @return {Function} The compiled function
484 compile: function() {
489 * Alias for {@link #applyTemplate}
490 * Returns an HTML fragment of this template with the specified values applied.
491 * @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'})
492 * @return {String} The HTML fragment
493 * @member Ext.XTemplate
496 this.createAlias('apply', 'applyTemplate');