Upgrade to ExtJS 3.1.1 - Released 02/08/2010
[extjs.git] / src / util / XTemplate.js
1 /*!
2  * Ext JS Library 3.1.1
3  * Copyright(c) 2006-2010 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.XTemplate
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>
18  * </ul></div></p>
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>
28  * </ul></div></p>
29  * 
30  * <p>For example usage {@link #XTemplate see the constructor}.</p>  
31  *   
32  * @constructor
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>
36  * 
37  * <div class="mdetail-params"><ul>
38  * 
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>
42  * <pre><code>
43 var data = {
44     name: 'Jack Slocum',
45     title: 'Lead Developer',
46     company: 'Ext JS, LLC',
47     email: 'jack@extjs.com',
48     address: '4 Red Bulls Drive',
49     city: 'Cleveland',
50     state: 'Ohio',
51     zip: '44102',
52     drinks: ['Red Bull', 'Coffee', 'Water'],
53     kids: [{
54         name: 'Sara Grace',
55         age:3
56     },{
57         name: 'Zachary',
58         age:2
59     },{
60         name: 'John James',
61         age:0
62     }]
63 };
64  * </code></pre>
65  * </div>
66  * </li>
67  * 
68  * 
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:
73  * <ul>
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
76  * array.</li>
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>
80  * </ul>
81  * </p>
82  * <pre><code>
83 &lt;tpl <b>for</b>=".">...&lt;/tpl>       // loop through array at root node
84 &lt;tpl <b>for</b>="foo">...&lt;/tpl>     // loop through array at foo node
85 &lt;tpl <b>for</b>="foo.bar">...&lt;/tpl> // loop through array at foo.bar node
86  * </code></pre>
87  * Using the sample data above:
88  * <pre><code>
89 var tpl = new Ext.XTemplate(
90     '&lt;p>Kids: ',
91     '&lt;tpl <b>for</b>=".">',       // process the data.kids node
92         '&lt;p>{#}. {name}&lt;/p>',  // use current array index to autonumber
93     '&lt;/tpl>&lt;/p>'
94 );
95 tpl.overwrite(panel.body, data.kids); // pass the kids property of the data object
96  * </code></pre>
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>
99  * <pre><code>
100 var tpl = new Ext.XTemplate(
101     '&lt;p>Name: {name}&lt;/p>',
102     '&lt;p>Title: {title}&lt;/p>',
103     '&lt;p>Company: {company}&lt;/p>',
104     '&lt;p>Kids: ',
105     '&lt;tpl <b>for="kids"</b>>',     // interrogate the kids property within the data
106         '&lt;p>{name}&lt;/p>',
107     '&lt;/tpl>&lt;/p>'
108 );
109 tpl.overwrite(panel.body, data);  // pass the root node of the data object
110  * </code></pre>
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>
114  * <pre><code>
115 var tpl = new Ext.XTemplate(
116     '&lt;p>{name}\&#39;s favorite beverages:&lt;/p>',
117     '&lt;tpl for="drinks">',
118        '&lt;div> - {.}&lt;/div>',
119     '&lt;/tpl>'
120 );
121 tpl.overwrite(panel.body, data);
122  * </code></pre>
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>
125  * <pre><code>
126 var tpl = new Ext.XTemplate(
127     '&lt;p>Name: {name}&lt;/p>',
128     '&lt;p>Kids: ',
129     '&lt;tpl for="kids">',
130         '&lt;tpl if="age > 1">',
131             '&lt;p>{name}&lt;/p>',
132             '&lt;p>Dad: {<b>parent</b>.name}&lt;/p>',
133         '&lt;/tpl>',
134     '&lt;/tpl>&lt;/p>'
135 );
136 tpl.overwrite(panel.body, data);
137  * </code></pre>
138  * </div>
139  * </li>
140  * 
141  * 
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 &mdash; if needed, two opposite
149  * <tt>if</tt> statements should be used.</li>
150  * </ul></div>
151  * <pre><code>
152 &lt;tpl if="age &gt; 1 &amp;&amp; age &lt; 10">Child&lt;/tpl>
153 &lt;tpl if="age >= 10 && age < 18">Teenager&lt;/tpl>
154 &lt;tpl <b>if</b>="this.isGirl(name)">...&lt;/tpl>
155 &lt;tpl <b>if</b>="id==\'download\'">...&lt;/tpl>
156 &lt;tpl <b>if</b>="needsIcon">&lt;img src="{icon}" class="{iconCls}"/>&lt;/tpl>
157 // no good:
158 &lt;tpl if="name == "Jack"">Hello&lt;/tpl>
159 // encode &#34; if it is part of the condition, e.g.
160 &lt;tpl if="name == &#38;quot;Jack&#38;quot;">Hello&lt;/tpl>
161  * </code></pre>
162  * Using the sample data above:
163  * <pre><code>
164 var tpl = new Ext.XTemplate(
165     '&lt;p>Name: {name}&lt;/p>',
166     '&lt;p>Kids: ',
167     '&lt;tpl for="kids">',
168         '&lt;tpl if="age > 1">',
169             '&lt;p>{name}&lt;/p>',
170         '&lt;/tpl>',
171     '&lt;/tpl>&lt;/p>'
172 );
173 tpl.overwrite(panel.body, data);
174  * </code></pre>
175  * </div>
176  * </li>
177  * 
178  * 
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>
183  * + - * /
184  * </pre>
185  * For example:
186  * <pre><code>
187 var tpl = new Ext.XTemplate(
188     '&lt;p>Name: {name}&lt;/p>',
189     '&lt;p>Kids: ',
190     '&lt;tpl for="kids">',
191         '&lt;tpl if="age &amp;gt; 1">',  // <-- Note that the &gt; is encoded
192             '&lt;p>{#}: {name}&lt;/p>',  // <-- Auto-number each item
193             '&lt;p>In 5 Years: {age+5}&lt;/p>',  // <-- Basic math
194             '&lt;p>Dad: {parent.name}&lt;/p>',
195         '&lt;/tpl>',
196     '&lt;/tpl>&lt;/p>'
197 );
198 tpl.overwrite(panel.body, data);
199 </code></pre>
200  * </div>
201  * </li>
202  *
203  * 
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:
208  * <ul>
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>
217  * </ul>
218  * This example demonstrates basic row striping using an inline code block and the
219  * <tt>xindex</tt> variable:</p>
220  * <pre><code>
221 var tpl = new Ext.XTemplate(
222     '&lt;p>Name: {name}&lt;/p>',
223     '&lt;p>Company: {[values.company.toUpperCase() + ", " + values.title]}&lt;/p>',
224     '&lt;p>Kids: ',
225     '&lt;tpl for="kids">',
226        '&lt;div class="{[xindex % 2 === 0 ? "even" : "odd"]}">',
227         '{name}',
228         '&lt;/div>',
229     '&lt;/tpl>&lt;/p>'
230 );
231 tpl.overwrite(panel.body, data);
232  * </code></pre>
233  * </div>
234  * </li>
235  * 
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>
240  * <pre><code>
241 var tpl = new Ext.XTemplate(
242     '&lt;p>Name: {name}&lt;/p>',
243     '&lt;p>Kids: ',
244     '&lt;tpl for="kids">',
245         '&lt;tpl if="this.isGirl(name)">',
246             '&lt;p>Girl: {name} - {age}&lt;/p>',
247         '&lt;/tpl>',
248         // use opposite if statement to simulate 'else' processing:
249         '&lt;tpl if="this.isGirl(name) == false">',
250             '&lt;p>Boy: {name} - {age}&lt;/p>',
251         '&lt;/tpl>',
252         '&lt;tpl if="this.isBaby(age)">',
253             '&lt;p>{name} is a baby!&lt;/p>',
254         '&lt;/tpl>',
255     '&lt;/tpl>&lt;/p>',
256     {
257         // XTemplate configuration:
258         compiled: true,
259         disableFormats: true,
260         // member functions:
261         isGirl: function(name){
262             return name == 'Sara Grace';
263         },
264         isBaby: function(age){
265             return age < 1;
266         }
267     }
268 );
269 tpl.overwrite(panel.body, data);
270  * </code></pre>
271  * </div>
272  * </li>
273  * 
274  * </ul></div>
275  * 
276  * @param {Mixed} config
277  */
278 Ext.XTemplate = function(){
279     Ext.XTemplate.superclass.constructor.apply(this, arguments);
280
281     var me = this,
282         s = me.html,
283         re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
284         nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
285         ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
286         execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
287         m,
288         id = 0,
289         tpls = [],
290         VALUES = 'values',
291         PARENT = 'parent',
292         XINDEX = 'xindex',
293         XCOUNT = 'xcount',
294         RETURN = 'return ',
295         WITHVALUES = 'with(values){ ';
296
297     s = ['<tpl>', s, '</tpl>'].join('');
298
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),
303                 exp = null,
304                 fn = null,
305                 exec = null,
306                 name = m2 && m2[1] ? m2[1] : '';
307
308        if (m3) {
309            exp = m3 && m3[1] ? m3[1] : null;
310            if(exp){
311                fn = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + RETURN +(Ext.util.Format.htmlDecode(exp))+'; }');
312            }
313        }
314        if (m4) {
315            exp = m4 && m4[1] ? m4[1] : null;
316            if(exp){
317                exec = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES +(Ext.util.Format.htmlDecode(exp))+'; }');
318            }
319        }
320        if(name){
321            switch(name){
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 + '; }');
325            }
326        }
327        tpls.push({
328             id: id,
329             target: name,
330             exec: exec,
331             test: fn,
332             body: m[1]||''
333         });
334        s = s.replace(m[0], '{xtpl'+ id + '}');
335        ++id;
336     }
337         Ext.each(tpls, function(t) {
338         me.compileTpl(t);
339     });
340     me.master = tpls[tpls.length-1];
341     me.tpls = tpls;
342 };
343 Ext.extend(Ext.XTemplate, Ext.Template, {
344     // private
345     re : /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\\]\s?[\d\.\+\-\*\\\(\)]+)?\}/g,
346     // private
347     codeRe : /\{\[((?:\\\]|.|\n)*?)\]\}/g,
348
349     // private
350     applySubTemplate : function(id, values, parent, xindex, xcount){
351         var me = this,
352                 len,
353                 t = me.tpls[id],
354                 vs,
355                 buf = [];
356         if ((t.test && !t.test.call(me, values, parent, xindex, xcount)) ||
357             (t.exec && t.exec.call(me, values, parent, xindex, xcount))) {
358             return '';
359         }
360         vs = t.target ? t.target.call(me, values, parent) : values;
361         len = vs.length;
362         parent = t.target ? values : parent;
363         if(t.target && Ext.isArray(vs)){
364                 Ext.each(vs, function(v, i) {
365                 buf[buf.length] = t.compiled.call(me, v, parent, i+1, len);
366             });
367             return buf.join('');
368         }
369         return t.compiled.call(me, vs, parent, xindex, xcount);
370     },
371
372     // private
373     compileTpl : function(tpl){
374         var fm = Ext.util.Format,
375                 useF = this.disableFormats !== true,
376             sep = Ext.isGecko ? "+" : ",",
377             body;
378
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+"'";
382             }
383             var v;
384             if(name === '.'){
385                 v = 'values';
386             }else if(name === '#'){
387                 v = 'xindex';
388             }else if(name.indexOf('.') != -1){
389                 v = name;
390             }else{
391                 v = "values['" + name + "']";
392             }
393             if(math){
394                 v = '(' + v + math + ')';
395             }
396             if (format && useF) {
397                 args = args ? ',' + args : "";
398                 if(format.substr(0, 5) != "this."){
399                     format = "fm." + format + '(';
400                 }else{
401                     format = 'this.call("'+ format.substr(5) + '", ';
402                     args = ", values";
403                 }
404             } else {
405                 args= ''; format = "("+v+" === undefined ? '' : ";
406             }
407             return "'"+ sep + format + v + args + ")"+sep+"'";
408         }
409
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 + "'";
413         }
414
415         // branched to use + in gecko and [].join() in others
416         if(Ext.isGecko){
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) +
419                     "';};";
420         }else{
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('');
425         }
426         eval(body);
427         return this;
428     },
429
430     /**
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
434      */
435     applyTemplate : function(values){
436         return this.master.compiled.call(this, values, {}, 1, 1);
437     },
438
439     /**
440      * Compile the template to a function for optimized performance.  Recommended if the template will be used frequently.
441      * @return {Function} The compiled function
442      */
443     compile : function(){return this;}
444
445     /**
446      * @property re
447      * @hide
448      */
449     /**
450      * @property disableFormats
451      * @hide
452      */
453     /**
454      * @method set
455      * @hide
456      */
457
458 });
459 /**
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
465  * @method apply
466  */
467 Ext.XTemplate.prototype.apply = Ext.XTemplate.prototype.applyTemplate;
468
469 /**
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
473  * @static
474  */
475 Ext.XTemplate.from = function(el){
476     el = Ext.getDom(el);
477     return new Ext.XTemplate(el.value || el.innerHTML);
478 };