Upgrade to ExtJS 3.0.0 - Released 07/06/2009
[extjs.git] / src / util / XTemplate.js
1 /*!
2  * Ext JS Library 3.0.0
3  * Copyright(c) 2006-2009 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 autofilling arrays, conditional processing with
11  * basic comparison operators, sub-templates, basic math function support, special built-in template variables,
12  * inline code execution and more.  XTemplate also provides the templating mechanism built into {@link Ext.DataView}.</p>
13  * <p>XTemplate supports many special tags and built-in operators that aren't defined as part of the API, but are
14  * supported in the templates that can be created.  The following examples demonstrate all of the supported features.
15  * This is the data object used for reference in each code example:</p>
16  * <pre><code>
17 var data = {
18     name: 'Jack Slocum',
19     title: 'Lead Developer',
20     company: 'Ext JS, LLC',
21     email: 'jack@extjs.com',
22     address: '4 Red Bulls Drive',
23     city: 'Cleveland',
24     state: 'Ohio',
25     zip: '44102',
26     drinks: ['Red Bull', 'Coffee', 'Water'],
27     kids: [{
28         name: 'Sara Grace',
29         age:3
30     },{
31         name: 'Zachary',
32         age:2
33     },{
34         name: 'John James',
35         age:0
36     }]
37 };
38  * </code></pre>
39  * <p><b>Auto filling of arrays</b><br/>The <tt>tpl</tt> tag and the <tt>for</tt> operator are used
40  * to process the provided data object. If <tt>for="."</tt> is specified, the data object provided
41  * is examined. If the variable in <tt>for</tt> is an array, it will auto-fill, repeating the template
42  * block inside the <tt>tpl</tt> tag for each item in the array:</p>
43  * <pre><code>
44 var tpl = new Ext.XTemplate(
45     '&lt;p>Kids: ',
46     '&lt;tpl for=".">',
47         '&lt;p>{name}&lt;/p>',
48     '&lt;/tpl>&lt;/p>'
49 );
50 tpl.overwrite(panel.body, data.kids); // pass the kids property of the data object
51  * </code></pre>
52  * <p><b>Scope switching</b><br/>The <tt>for</tt> property can be leveraged to access specified members
53  * of the provided data object to populate the template:</p>
54  * <pre><code>
55 var tpl = new Ext.XTemplate(
56     '&lt;p>Name: {name}&lt;/p>',
57     '&lt;p>Title: {title}&lt;/p>',
58     '&lt;p>Company: {company}&lt;/p>',
59     '&lt;p>Kids: ',
60     '&lt;tpl <b>for="kids"</b>>', // interrogate the kids property within the data
61         '&lt;p>{name}&lt;/p>',
62     '&lt;/tpl>&lt;/p>'
63 );
64 tpl.overwrite(panel.body, data);
65  * </code></pre>
66  * <p><b>Access to parent object from within sub-template scope</b><br/>When processing a sub-template, for example while
67  * looping through a child array, you can access the parent object's members via the <tt>parent</tt> object:</p>
68  * <pre><code>
69 var tpl = new Ext.XTemplate(
70     '&lt;p>Name: {name}&lt;/p>',
71     '&lt;p>Kids: ',
72     '&lt;tpl for="kids">',
73         '&lt;tpl if="age &amp;gt; 1">',  // <-- Note that the &gt; is encoded
74             '&lt;p>{name}&lt;/p>',
75             '&lt;p>Dad: {parent.name}&lt;/p>',
76         '&lt;/tpl>',
77     '&lt;/tpl>&lt;/p>'
78 );
79 tpl.overwrite(panel.body, data);
80 </code></pre>
81  * <p><b>Array item index and basic math support</b> <br/>While processing an array, the special variable <tt>{#}</tt>
82  * will provide the current array index + 1 (starts at 1, not 0). Templates also support the basic math operators
83  * + - * and / that can be applied directly on numeric data values:</p>
84  * <pre><code>
85 var tpl = new Ext.XTemplate(
86     '&lt;p>Name: {name}&lt;/p>',
87     '&lt;p>Kids: ',
88     '&lt;tpl for="kids">',
89         '&lt;tpl if="age &amp;gt; 1">',  // <-- Note that the &gt; is encoded
90             '&lt;p>{#}: {name}&lt;/p>',  // <-- Auto-number each item
91             '&lt;p>In 5 Years: {age+5}&lt;/p>',  // <-- Basic math
92             '&lt;p>Dad: {parent.name}&lt;/p>',
93         '&lt;/tpl>',
94     '&lt;/tpl>&lt;/p>'
95 );
96 tpl.overwrite(panel.body, data);
97 </code></pre>
98  * <p><b>Auto-rendering of flat arrays</b> <br/>Flat arrays that contain values (and not objects) can be auto-rendered
99  * using the special <tt>{.}</tt> variable inside a loop.  This variable will represent the value of
100  * the array at the current index:</p>
101  * <pre><code>
102 var tpl = new Ext.XTemplate(
103     '&lt;p>{name}\'s favorite beverages:&lt;/p>',
104     '&lt;tpl for="drinks">',
105        '&lt;div> - {.}&lt;/div>',
106     '&lt;/tpl>'
107 );
108 tpl.overwrite(panel.body, data);
109 </code></pre>
110  * <p><b>Basic conditional logic</b> <br/>Using the <tt>tpl</tt> tag and the <tt>if</tt>
111  * operator you can provide conditional checks for deciding whether or not to render specific parts of the template.
112  * Note that there is no <tt>else</tt> operator &mdash; if needed, you should use two opposite <tt>if</tt> statements.
113  * Properly-encoded attributes are required as seen in the following example:</p>
114  * <pre><code>
115 var tpl = new Ext.XTemplate(
116     '&lt;p>Name: {name}&lt;/p>',
117     '&lt;p>Kids: ',
118     '&lt;tpl for="kids">',
119         '&lt;tpl if="age &amp;gt; 1">',  // <-- Note that the &gt; is encoded
120             '&lt;p>{name}&lt;/p>',
121         '&lt;/tpl>',
122     '&lt;/tpl>&lt;/p>'
123 );
124 tpl.overwrite(panel.body, data);
125 </code></pre>
126  * <p><b>Ability to execute arbitrary inline code</b> <br/>In an XTemplate, anything between {[ ... ]}  is considered
127  * code to be executed in the scope of the template. There are some special variables available in that code:
128  * <ul>
129  * <li><b><tt>values</tt></b>: The values in the current scope. If you are using scope changing sub-templates, you
130  * can change what <tt>values</tt> is.</li>
131  * <li><b><tt>parent</tt></b>: The scope (values) of the ancestor template.</li>
132  * <li><b><tt>xindex</tt></b>: If you are in a looping template, the index of the loop you are in (1-based).</li>
133  * <li><b><tt>xcount</tt></b>: If you are in a looping template, the total length of the array you are looping.</li>
134  * <li><b><tt>fm</tt></b>: An alias for <tt>Ext.util.Format</tt>.</li>
135  * </ul>
136  * This example demonstrates basic row striping using an inline code block and the <tt>xindex</tt> variable:</p>
137  * <pre><code>
138 var tpl = new Ext.XTemplate(
139     '&lt;p>Name: {name}&lt;/p>',
140     '&lt;p>Company: {[values.company.toUpperCase() + ", " + values.title]}&lt;/p>',
141     '&lt;p>Kids: ',
142     '&lt;tpl for="kids">',
143        '&lt;div class="{[xindex % 2 === 0 ? "even" : "odd"]}">',
144         '{name}',
145         '&lt;/div>',
146     '&lt;/tpl>&lt;/p>'
147 );
148 tpl.overwrite(panel.body, data);
149 </code></pre>
150  * <p><b>Template member functions</b> <br/>One or more member functions can be defined directly on the config
151  * object passed into the XTemplate constructor for more complex processing:</p>
152  * <pre><code>
153 var tpl = new Ext.XTemplate(
154     '&lt;p>Name: {name}&lt;/p>',
155     '&lt;p>Kids: ',
156     '&lt;tpl for="kids">',
157         '&lt;tpl if="this.isGirl(name)">',
158             '&lt;p>Girl: {name} - {age}&lt;/p>',
159         '&lt;/tpl>',
160         '&lt;tpl if="this.isGirl(name) == false">',
161             '&lt;p>Boy: {name} - {age}&lt;/p>',
162         '&lt;/tpl>',
163         '&lt;tpl if="this.isBaby(age)">',
164             '&lt;p>{name} is a baby!&lt;/p>',
165         '&lt;/tpl>',
166     '&lt;/tpl>&lt;/p>', {
167      isGirl: function(name){
168          return name == 'Sara Grace';
169      },
170      isBaby: function(age){
171         return age < 1;
172      }
173 });
174 tpl.overwrite(panel.body, data);
175 </code></pre>
176  * @constructor
177  * @param {String/Array/Object} parts The HTML fragment or an array of fragments to join(""), or multiple arguments
178  * to join("") that can also include a config object
179  */
180 Ext.XTemplate = function(){
181     Ext.XTemplate.superclass.constructor.apply(this, arguments);
182
183     var me = this,
184         s = me.html,
185         re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
186         nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
187         ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
188         execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
189         m,
190         id = 0,
191         tpls = [],
192         VALUES = 'values',
193         PARENT = 'parent',
194         XINDEX = 'xindex',
195         XCOUNT = 'xcount',
196         RETURN = 'return ',
197         WITHVALUES = 'with(values){ ';
198
199     s = ['<tpl>', s, '</tpl>'].join('');
200
201     while((m = s.match(re))){
202         var m2 = m[0].match(nameRe),
203                         m3 = m[0].match(ifRe),
204                 m4 = m[0].match(execRe),
205                 exp = null,
206                 fn = null,
207                 exec = null,
208                 name = m2 && m2[1] ? m2[1] : '';
209
210        if (m3) {
211            exp = m3 && m3[1] ? m3[1] : null;
212            if(exp){
213                fn = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + RETURN +(Ext.util.Format.htmlDecode(exp))+'; }');
214            }
215        }
216        if (m4) {
217            exp = m4 && m4[1] ? m4[1] : null;
218            if(exp){
219                exec = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES +(Ext.util.Format.htmlDecode(exp))+'; }');
220            }
221        }
222        if(name){
223            switch(name){
224                case '.': name = new Function(VALUES, PARENT, WITHVALUES + RETURN + VALUES + '; }'); break;
225                case '..': name = new Function(VALUES, PARENT, WITHVALUES + RETURN + PARENT + '; }'); break;
226                default: name = new Function(VALUES, PARENT, WITHVALUES + RETURN + name + '; }');
227            }
228        }
229        tpls.push({
230             id: id,
231             target: name,
232             exec: exec,
233             test: fn,
234             body: m[1]||''
235         });
236        s = s.replace(m[0], '{xtpl'+ id + '}');
237        ++id;
238     }
239         Ext.each(tpls, function(t) {
240         me.compileTpl(t);
241     });
242     me.master = tpls[tpls.length-1];
243     me.tpls = tpls;
244 };
245 Ext.extend(Ext.XTemplate, Ext.Template, {
246     // private
247     re : /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\\]\s?[\d\.\+\-\*\\\(\)]+)?\}/g,
248     // private
249     codeRe : /\{\[((?:\\\]|.|\n)*?)\]\}/g,
250
251     // private
252     applySubTemplate : function(id, values, parent, xindex, xcount){
253         var me = this,
254                 len,
255                 t = me.tpls[id],
256                 vs,
257                 buf = [];
258         if ((t.test && !t.test.call(me, values, parent, xindex, xcount)) ||
259             (t.exec && t.exec.call(me, values, parent, xindex, xcount))) {
260             return '';
261         }
262         vs = t.target ? t.target.call(me, values, parent) : values;
263         len = vs.length;
264         parent = t.target ? values : parent;
265         if(t.target && Ext.isArray(vs)){
266                 Ext.each(vs, function(v, i) {
267                 buf[buf.length] = t.compiled.call(me, v, parent, i+1, len);
268             });
269             return buf.join('');
270         }
271         return t.compiled.call(me, vs, parent, xindex, xcount);
272     },
273
274     // private
275     compileTpl : function(tpl){
276         var fm = Ext.util.Format,
277                 useF = this.disableFormats !== true,
278             sep = Ext.isGecko ? "+" : ",",
279             body;
280
281         function fn(m, name, format, args, math){
282             if(name.substr(0, 4) == 'xtpl'){
283                 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent, xindex, xcount)'+sep+"'";
284             }
285             var v;
286             if(name === '.'){
287                 v = 'values';
288             }else if(name === '#'){
289                 v = 'xindex';
290             }else if(name.indexOf('.') != -1){
291                 v = name;
292             }else{
293                 v = "values['" + name + "']";
294             }
295             if(math){
296                 v = '(' + v + math + ')';
297             }
298             if (format && useF) {
299                 args = args ? ',' + args : "";
300                 if(format.substr(0, 5) != "this."){
301                     format = "fm." + format + '(';
302                 }else{
303                     format = 'this.call("'+ format.substr(5) + '", ';
304                     args = ", values";
305                 }
306             } else {
307                 args= ''; format = "("+v+" === undefined ? '' : ";
308             }
309             return "'"+ sep + format + v + args + ")"+sep+"'";
310         }
311
312         function codeFn(m, code){
313             return "'"+ sep +'('+code+')'+sep+"'";
314         }
315
316         // branched to use + in gecko and [].join() in others
317         if(Ext.isGecko){
318             body = "tpl.compiled = function(values, parent, xindex, xcount){ return '" +
319                    tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn) +
320                     "';};";
321         }else{
322             body = ["tpl.compiled = function(values, parent, xindex, xcount){ return ['"];
323             body.push(tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn));
324             body.push("'].join('');};");
325             body = body.join('');
326         }
327         eval(body);
328         return this;
329     },
330
331     /**
332      * Returns an HTML fragment of this template with the specified values applied.
333      * @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'})
334      * @return {String} The HTML fragment
335      */
336     applyTemplate : function(values){
337         return this.master.compiled.call(this, values, {}, 1, 1);
338     },
339
340     /**
341      * Compile the template to a function for optimized performance.  Recommended if the template will be used frequently.
342      * @return {Function} The compiled function
343      */
344     compile : function(){return this;}
345
346     /**
347      * @property re
348      * @hide
349      */
350     /**
351      * @property disableFormats
352      * @hide
353      */
354     /**
355      * @method set
356      * @hide
357      */
358
359 });
360 /**
361  * Alias for {@link #applyTemplate}
362  * Returns an HTML fragment of this template with the specified values applied.
363  * @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'})
364  * @return {String} The HTML fragment
365  * @member Ext.XTemplate
366  * @method apply
367  */
368 Ext.XTemplate.prototype.apply = Ext.XTemplate.prototype.applyTemplate;
369
370 /**
371  * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
372  * @param {String/HTMLElement} el A DOM element or its id
373  * @return {Ext.Template} The created template
374  * @static
375  */
376 Ext.XTemplate.from = function(el){
377     el = Ext.getDom(el);
378     return new Ext.XTemplate(el.value || el.innerHTML);
379 };