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