Upgrade to ExtJS 4.0.2 - Released 06/09/2011
[extjs.git] / src / XTemplate.js
1 /*
2
3 This file is part of Ext JS 4
4
5 Copyright (c) 2011 Sencha Inc
6
7 Contact:  http://www.sencha.com/contact
8
9 GNU General Public License Usage
10 This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file.  Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
11
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
13
14 */
15 /**
16  * @class Ext.XTemplate
17  * @extends Ext.Template
18  * <p>A template class that supports advanced functionality like:<div class="mdetail-params"><ul>
19  * <li>Autofilling arrays using templates and sub-templates</li>
20  * <li>Conditional processing with basic comparison operators</li>
21  * <li>Basic math function support</li>
22  * <li>Execute arbitrary inline code with special built-in template variables</li>
23  * <li>Custom member functions</li>
24  * <li>Many special tags and built-in operators that aren't defined as part of
25  * the API, but are supported in the templates that can be created</li>
26  * </ul></div></p>
27  * <p>XTemplate provides the templating mechanism built into:<div class="mdetail-params"><ul>
28  * <li>{@link Ext.view.View}</li>
29  * </ul></div></p>
30  *
31  * The {@link Ext.Template} describes
32  * the acceptable parameters to pass to the constructor. The following
33  * examples demonstrate all of the supported features.</p>
34  *
35  * <div class="mdetail-params"><ul>
36  *
37  * <li><b><u>Sample Data</u></b>
38  * <div class="sub-desc">
39  * <p>This is the data object used for reference in each code example:</p>
40  * <pre><code>
41 var data = {
42 name: 'Tommy Maintz',
43 title: 'Lead Developer',
44 company: 'Sencha Inc.',
45 email: 'tommy@sencha.com',
46 address: '5 Cups Drive',
47 city: 'Palo Alto',
48 state: 'CA',
49 zip: '44102',
50 drinks: ['Coffee', 'Soda', 'Water'],
51 kids: [{
52         name: 'Joshua',
53         age:3
54     },{
55         name: 'Matthew',
56         age:2
57     },{
58         name: 'Solomon',
59         age:0
60 }]
61 };
62  </code></pre>
63  * </div>
64  * </li>
65  *
66  *
67  * <li><b><u>Auto filling of arrays</u></b>
68  * <div class="sub-desc">
69  * <p>The <b><tt>tpl</tt></b> tag and the <b><tt>for</tt></b> operator are used
70  * to process the provided data object:
71  * <ul>
72  * <li>If the value specified in <tt>for</tt> is an array, it will auto-fill,
73  * repeating the template block inside the <tt>tpl</tt> tag for each item in the
74  * array.</li>
75  * <li>If <tt>for="."</tt> is specified, the data object provided is examined.</li>
76  * <li>While processing an array, the special variable <tt>{#}</tt>
77  * will provide the current array index + 1 (starts at 1, not 0).</li>
78  * </ul>
79  * </p>
80  * <pre><code>
81 &lt;tpl <b>for</b>=".">...&lt;/tpl>       // loop through array at root node
82 &lt;tpl <b>for</b>="foo">...&lt;/tpl>     // loop through array at foo node
83 &lt;tpl <b>for</b>="foo.bar">...&lt;/tpl> // loop through array at foo.bar node
84  </code></pre>
85  * Using the sample data above:
86  * <pre><code>
87 var tpl = new Ext.XTemplate(
88     '&lt;p>Kids: ',
89     '&lt;tpl <b>for</b>=".">',       // process the data.kids node
90         '&lt;p>{#}. {name}&lt;/p>',  // use current array index to autonumber
91     '&lt;/tpl>&lt;/p>'
92 );
93 tpl.overwrite(panel.body, data.kids); // pass the kids property of the data object
94  </code></pre>
95  * <p>An example illustrating how the <b><tt>for</tt></b> property can be leveraged
96  * to access specified members of the provided data object to populate the template:</p>
97  * <pre><code>
98 var tpl = new Ext.XTemplate(
99     '&lt;p>Name: {name}&lt;/p>',
100     '&lt;p>Title: {title}&lt;/p>',
101     '&lt;p>Company: {company}&lt;/p>',
102     '&lt;p>Kids: ',
103     '&lt;tpl <b>for="kids"</b>>',     // interrogate the kids property within the data
104         '&lt;p>{name}&lt;/p>',
105     '&lt;/tpl>&lt;/p>'
106 );
107 tpl.overwrite(panel.body, data);  // pass the root node of the data object
108  </code></pre>
109  * <p>Flat arrays that contain values (and not objects) can be auto-rendered
110  * using the special <b><tt>{.}</tt></b> variable inside a loop.  This variable
111  * will represent the value of the array at the current index:</p>
112  * <pre><code>
113 var tpl = new Ext.XTemplate(
114     '&lt;p>{name}\&#39;s favorite beverages:&lt;/p>',
115     '&lt;tpl for="drinks">',
116         '&lt;div> - {.}&lt;/div>',
117     '&lt;/tpl>'
118 );
119 tpl.overwrite(panel.body, data);
120  </code></pre>
121  * <p>When processing a sub-template, for example while looping through a child array,
122  * you can access the parent object's members via the <b><tt>parent</tt></b> object:</p>
123  * <pre><code>
124 var tpl = new Ext.XTemplate(
125     '&lt;p>Name: {name}&lt;/p>',
126     '&lt;p>Kids: ',
127     '&lt;tpl for="kids">',
128         '&lt;tpl if="age &amp;gt; 1">',
129             '&lt;p>{name}&lt;/p>',
130             '&lt;p>Dad: {<b>parent</b>.name}&lt;/p>',
131         '&lt;/tpl>',
132     '&lt;/tpl>&lt;/p>'
133 );
134 tpl.overwrite(panel.body, data);
135  </code></pre>
136  * </div>
137  * </li>
138  *
139  *
140  * <li><b><u>Conditional processing with basic comparison operators</u></b>
141  * <div class="sub-desc">
142  * <p>The <b><tt>tpl</tt></b> tag and the <b><tt>if</tt></b> operator are used
143  * to provide conditional checks for deciding whether or not to render specific
144  * parts of the template. Notes:<div class="sub-desc"><ul>
145  * <li>Double quotes must be encoded if used within the conditional</li>
146  * <li>There is no <tt>else</tt> operator &mdash; if needed, two opposite
147  * <tt>if</tt> statements should be used.</li>
148  * </ul></div>
149  * <pre><code>
150 &lt;tpl if="age &gt; 1 &amp;&amp; age &lt; 10">Child&lt;/tpl>
151 &lt;tpl if="age >= 10 && age < 18">Teenager&lt;/tpl>
152 &lt;tpl <b>if</b>="this.isGirl(name)">...&lt;/tpl>
153 &lt;tpl <b>if</b>="id==\'download\'">...&lt;/tpl>
154 &lt;tpl <b>if</b>="needsIcon">&lt;img src="{icon}" class="{iconCls}"/>&lt;/tpl>
155 // no good:
156 &lt;tpl if="name == "Tommy"">Hello&lt;/tpl>
157 // encode &#34; if it is part of the condition, e.g.
158 &lt;tpl if="name == &#38;quot;Tommy&#38;quot;">Hello&lt;/tpl>
159  * </code></pre>
160  * Using the sample data above:
161  * <pre><code>
162 var tpl = new Ext.XTemplate(
163     '&lt;p>Name: {name}&lt;/p>',
164     '&lt;p>Kids: ',
165     '&lt;tpl for="kids">',
166         '&lt;tpl if="age &amp;gt; 1">',
167             '&lt;p>{name}&lt;/p>',
168         '&lt;/tpl>',
169     '&lt;/tpl>&lt;/p>'
170 );
171 tpl.overwrite(panel.body, data);
172  </code></pre>
173  * </div>
174  * </li>
175  *
176  *
177  * <li><b><u>Basic math support</u></b>
178  * <div class="sub-desc">
179  * <p>The following basic math operators may be applied directly on numeric
180  * data values:</p><pre>
181  * + - * /
182  * </pre>
183  * For example:
184  * <pre><code>
185 var tpl = new Ext.XTemplate(
186     '&lt;p>Name: {name}&lt;/p>',
187     '&lt;p>Kids: ',
188     '&lt;tpl for="kids">',
189         '&lt;tpl if="age &amp;gt; 1">',  // <-- Note that the &gt; is encoded
190             '&lt;p>{#}: {name}&lt;/p>',  // <-- Auto-number each item
191             '&lt;p>In 5 Years: {age+5}&lt;/p>',  // <-- Basic math
192             '&lt;p>Dad: {parent.name}&lt;/p>',
193         '&lt;/tpl>',
194     '&lt;/tpl>&lt;/p>'
195 );
196 tpl.overwrite(panel.body, data);
197  </code></pre>
198  * </div>
199  * </li>
200  *
201  *
202  * <li><b><u>Execute arbitrary inline code with special built-in template variables</u></b>
203  * <div class="sub-desc">
204  * <p>Anything between <code>{[ ... ]}</code> is considered code to be executed
205  * in the scope of the template. There are some special variables available in that code:
206  * <ul>
207  * <li><b><tt>values</tt></b>: The values in the current scope. If you are using
208  * scope changing sub-templates, you can change what <tt>values</tt> is.</li>
209  * <li><b><tt>parent</tt></b>: The scope (values) of the ancestor template.</li>
210  * <li><b><tt>xindex</tt></b>: If you are in a looping template, the index of the
211  * loop you are in (1-based).</li>
212  * <li><b><tt>xcount</tt></b>: If you are in a looping template, the total length
213  * of the array you are looping.</li>
214  * </ul>
215  * This example demonstrates basic row striping using an inline code block and the
216  * <tt>xindex</tt> variable:</p>
217  * <pre><code>
218 var tpl = new Ext.XTemplate(
219     '&lt;p>Name: {name}&lt;/p>',
220     '&lt;p>Company: {[values.company.toUpperCase() + ", " + values.title]}&lt;/p>',
221     '&lt;p>Kids: ',
222     '&lt;tpl for="kids">',
223         '&lt;div class="{[xindex % 2 === 0 ? "even" : "odd"]}">',
224         '{name}',
225         '&lt;/div>',
226     '&lt;/tpl>&lt;/p>'
227  );
228 tpl.overwrite(panel.body, data);
229  </code></pre>
230  * </div>
231  * </li>
232  *
233  * <li><b><u>Template member functions</u></b>
234  * <div class="sub-desc">
235  * <p>One or more member functions can be specified in a configuration
236  * object passed into the XTemplate constructor for more complex processing:</p>
237  * <pre><code>
238 var tpl = new Ext.XTemplate(
239     '&lt;p>Name: {name}&lt;/p>',
240     '&lt;p>Kids: ',
241     '&lt;tpl for="kids">',
242         '&lt;tpl if="this.isGirl(name)">',
243             '&lt;p>Girl: {name} - {age}&lt;/p>',
244         '&lt;/tpl>',
245          // use opposite if statement to simulate 'else' processing:
246         '&lt;tpl if="this.isGirl(name) == false">',
247             '&lt;p>Boy: {name} - {age}&lt;/p>',
248         '&lt;/tpl>',
249         '&lt;tpl if="this.isBaby(age)">',
250             '&lt;p>{name} is a baby!&lt;/p>',
251         '&lt;/tpl>',
252     '&lt;/tpl>&lt;/p>',
253     {
254         // XTemplate configuration:
255         compiled: true,
256         // member functions:
257         isGirl: function(name){
258            return name == 'Sara Grace';
259         },
260         isBaby: function(age){
261            return age < 1;
262         }
263     }
264 );
265 tpl.overwrite(panel.body, data);
266  </code></pre>
267  * </div>
268  * </li>
269  *
270  * </ul></div>
271  *
272  * @param {Mixed} config
273  */
274
275 Ext.define('Ext.XTemplate', {
276
277     /* Begin Definitions */
278
279     extend: 'Ext.Template',
280
281     statics: {
282         /**
283          * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
284          * @param {String/HTMLElement} el A DOM element or its id
285          * @return {Ext.Template} The created template
286          * @static
287          */
288         from: function(el, config) {
289             el = Ext.getDom(el);
290             return new this(el.value || el.innerHTML, config || {});
291         }
292     },
293
294     /* End Definitions */
295
296     argsRe: /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
297     nameRe: /^<tpl\b[^>]*?for="(.*?)"/,
298     ifRe: /^<tpl\b[^>]*?if="(.*?)"/,
299     execRe: /^<tpl\b[^>]*?exec="(.*?)"/,
300     constructor: function() {
301         this.callParent(arguments);
302
303         var me = this,
304             html = me.html,
305             argsRe = me.argsRe,
306             nameRe = me.nameRe,
307             ifRe = me.ifRe,
308             execRe = me.execRe,
309             id = 0,
310             tpls = [],
311             VALUES = 'values',
312             PARENT = 'parent',
313             XINDEX = 'xindex',
314             XCOUNT = 'xcount',
315             RETURN = 'return ',
316             WITHVALUES = 'with(values){ ',
317             m, matchName, matchIf, matchExec, exp, fn, exec, name, i;
318
319         html = ['<tpl>', html, '</tpl>'].join('');
320
321         while ((m = html.match(argsRe))) {
322             exp = null;
323             fn = null;
324             exec = null;
325             matchName = m[0].match(nameRe);
326             matchIf = m[0].match(ifRe);
327             matchExec = m[0].match(execRe);
328
329             exp = matchIf ? matchIf[1] : null;
330             if (exp) {
331                 fn = Ext.functionFactory(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + 'try{' + RETURN + Ext.String.htmlDecode(exp) + ';}catch(e){return;}}');
332             }
333
334             exp = matchExec ? matchExec[1] : null;
335             if (exp) {
336                 exec = Ext.functionFactory(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + Ext.String.htmlDecode(exp) + ';}');
337             }
338
339             name = matchName ? matchName[1] : null;
340             if (name) {
341                 if (name === '.') {
342                     name = VALUES;
343                 } else if (name === '..') {
344                     name = PARENT;
345                 }
346                 name = Ext.functionFactory(VALUES, PARENT, 'try{' + WITHVALUES + RETURN + name + ';}}catch(e){return;}');
347             }
348
349             tpls.push({
350                 id: id,
351                 target: name,
352                 exec: exec,
353                 test: fn,
354                 body: m[1] || ''
355             });
356
357             html = html.replace(m[0], '{xtpl' + id + '}');
358             id = id + 1;
359         }
360
361         for (i = tpls.length - 1; i >= 0; --i) {
362             me.compileTpl(tpls[i]);
363         }
364         me.master = tpls[tpls.length - 1];
365         me.tpls = tpls;
366     },
367
368     // @private
369     applySubTemplate: function(id, values, parent, xindex, xcount) {
370         var me = this, t = me.tpls[id];
371         return t.compiled.call(me, values, parent, xindex, xcount);
372     },
373     /**
374      * @cfg {RegExp} codeRe The regular expression used to match code variables (default: matches <tt>{[expression]}</tt>).
375      */
376     codeRe: /\{\[((?:\\\]|.|\n)*?)\]\}/g,
377
378     re: /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\/]\s?[\d\.\+\-\*\/\(\)]+)?\}/g,
379
380     // @private
381     compileTpl: function(tpl) {
382         var fm = Ext.util.Format,
383             me = this,
384             useFormat = me.disableFormats !== true,
385             body, bodyReturn, evaluatedFn;
386
387         function fn(m, name, format, args, math) {
388             var v;
389             // name is what is inside the {}
390             // Name begins with xtpl, use a Sub Template
391             if (name.substr(0, 4) == 'xtpl') {
392                 return "',this.applySubTemplate(" + name.substr(4) + ", values, parent, xindex, xcount),'";
393             }
394             // name = "." - Just use the values object.
395             if (name == '.') {
396                 // filter to not include arrays/objects/nulls
397                 v = 'Ext.Array.indexOf(["string", "number", "boolean"], typeof values) > -1 || Ext.isDate(values) ? values : ""';
398             }
399
400             // name = "#" - Use the xindex
401             else if (name == '#') {
402                 v = 'xindex';
403             }
404             else if (name.substr(0, 7) == "parent.") {
405                 v = name;
406             }
407             // name has a . in it - Use object literal notation, starting from values
408             else if (name.indexOf('.') != -1) {
409                 v = "values." + name;
410             }
411
412             // name is a property of values
413             else {
414                 v = "values['" + name + "']";
415             }
416             if (math) {
417                 v = '(' + v + math + ')';
418             }
419             if (format && useFormat) {
420                 args = args ? ',' + args : "";
421                 if (format.substr(0, 5) != "this.") {
422                     format = "fm." + format + '(';
423                 }
424                 else {
425                     format = 'this.' + format.substr(5) + '(';
426                 }
427             }
428             else {
429                 args = '';
430                 format = "(" + v + " === undefined ? '' : ";
431             }
432             return "'," + format + v + args + "),'";
433         }
434
435         function codeFn(m, code) {
436             // Single quotes get escaped when the template is compiled, however we want to undo this when running code.
437             return "',(" + code.replace(me.compileARe, "'") + "),'";
438         }
439
440         bodyReturn = tpl.body.replace(me.compileBRe, '\\n').replace(me.compileCRe, "\\'").replace(me.re, fn).replace(me.codeRe, codeFn);
441         body = "evaluatedFn = function(values, parent, xindex, xcount){return ['" + bodyReturn + "'].join('');};";
442         eval(body);
443
444         tpl.compiled = function(values, parent, xindex, xcount) {
445             var vs,
446                 length,
447                 buffer,
448                 i;
449
450             if (tpl.test && !tpl.test.call(me, values, parent, xindex, xcount)) {
451                 return '';
452             }
453
454             vs = tpl.target ? tpl.target.call(me, values, parent) : values;
455             if (!vs) {
456                return '';
457             }
458
459             parent = tpl.target ? values : parent;
460             if (tpl.target && Ext.isArray(vs)) {
461                 buffer = [];
462                 length = vs.length;
463                 if (tpl.exec) {
464                     for (i = 0; i < length; i++) {
465                         buffer[buffer.length] = evaluatedFn.call(me, vs[i], parent, i + 1, length);
466                         tpl.exec.call(me, vs[i], parent, i + 1, length);
467                     }
468                 } else {
469                     for (i = 0; i < length; i++) {
470                         buffer[buffer.length] = evaluatedFn.call(me, vs[i], parent, i + 1, length);
471                     }
472                 }
473                 return buffer.join('');
474             }
475
476             if (tpl.exec) {
477                 tpl.exec.call(me, vs, parent, xindex, xcount);
478             }
479             return evaluatedFn.call(me, vs, parent, xindex, xcount);
480         };
481
482         return this;
483     },
484
485     /**
486      * Returns an HTML fragment of this template with the specified values applied.
487      * @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'})
488      * @return {String} The HTML fragment
489      */
490     applyTemplate: function(values) {
491         return this.master.compiled.call(this, values, {}, 1, 1);
492     },
493
494     /**
495      * Compile the template to a function for optimized performance.  Recommended if the template will be used frequently.
496      * @return {Function} The compiled function
497      */
498     compile: function() {
499         return this;
500     }
501 }, function() {
502     /**
503      * Alias for {@link #applyTemplate}
504      * Returns an HTML fragment of this template with the specified values applied.
505      * @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'})
506      * @return {String} The HTML fragment
507      * @member Ext.XTemplate
508      * @method apply
509      */
510     this.createAlias('apply', 'applyTemplate');
511 });
512