Roo/XTemplate.js
[roojs1] / Roo / XTemplate.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11
12
13 /**
14  * @class Roo.XTemplate
15  * @extends Roo.Template
16  * Provides a template that can have nested templates for loops or conditionals. The syntax is:
17 <pre><code>
18 var t = new Roo.XTemplate(
19         '&lt;select name="{name}"&gt;',
20                 '&lt;tpl for="options"&gt;&lt;option value="{value:trim}"&gt;{text:ellipsis(10)}&lt;/option&gt;&lt;/tpl&gt;',
21         '&lt;/select&gt;'
22 );
23  
24 // then append, applying the master template values
25  </code></pre>
26  *
27  * Supported features:
28  *
29  *  Tags:
30  *    {a_variable} - output encoded.
31  *    {a_variable.format:("Y-m-d")} - call a method on the variable
32  *    {a_variable:raw} - unencoded output
33  *    {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
34  *    {a_variable:this.method_on_template(...)} - call a method on the template object.
35  *  
36  *  Tpl:
37  *      &lt;tpl for="a_variable or condition.."&gt;&lt;/tpl&gt;
38  *      &lt;tpl if="a_variable or condition"&gt;&lt;/tpl&gt;
39  *      &lt;tpl exec="some javascript"&gt;&lt;/tpl&gt;
40  *
41  *      &lt;tpl for="."&gt;&lt;/tpl&gt; - just iterate the property..
42  *      &lt;tpl for=".."&gt;&lt;/tpl&gt; - iterates with the parent (probably the template) 
43  *      
44  *      
45  */
46 Roo.XTemplate = function()
47 {
48     Roo.XTemplate.superclass.constructor.apply(this, arguments);
49     if (this.html) {
50         this.compile();
51     }
52 };
53
54
55 Roo.extend(Roo.XTemplate, Roo.Template, {
56
57     /**
58      *
59      * basic tag replacing syntax
60      * WORD:WORD()
61      *
62      * // you can fake an object call by doing this
63      *  x.t:(test,tesT) 
64      * 
65      */
66     re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
67
68     /**
69      * compile the template
70      *
71      * This is not recursive, so I'm not sure how nested templates are really going to be handled..
72      *
73      */
74     compile: function()
75     {
76         var s = this.html;
77      
78         s = ['<tpl>', s, '</tpl>'].join('');
79     
80         var re     = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
81             nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
82             ifRe   = /^<tpl\b[^>]*?if="(.*?)"/,
83             execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
84             namedRe = /^<tpl\b[^>]*?name="(\w+)"/,  // named templates..
85             m,
86             id     = 0,
87             tpls   = [];
88     
89         while(true == !!(m = s.match(re))){
90             var forMatch   = m[0].match(nameRe),
91                 ifMatch   = m[0].match(ifRe),
92                 execMatch   = m[0].match(execRe),
93                 namedMatch   = m[0].match(namedRe),
94                 
95                 exp  = null, 
96                 fn   = null,
97                 exec = null,
98                 name = forMatch && forMatch[1] ? forMatch[1] : '';
99                 
100             if (ifMatch) {
101                 // if - puts fn into test..
102                 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
103                 if(exp){
104                    fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
105                 }
106             }
107             
108             if (execMatch) {
109                 // exec - calls a function... returns empty if true is  returned.
110                 exp = execMatch && execMatch[1] ? execMatch[1] : null;
111                 if(exp){
112                    exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
113                 }
114             }
115             
116             
117             if (name) {
118                 // for = 
119                 switch(name){
120                     case '.':  name = new Function('values', 'parent', 'with(values){ return values; }'); break;
121                     case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
122                     default:   name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
123                 }
124             }
125             
126             
127             tpls.push({
128                 id:     namedMatch ? namedMatch[1] : id,
129                 target: name,
130                 exec:   exec,
131                 test:   fn,
132                 body:   m[1] || ''
133             });
134             if (namedMatch) {
135                 s = s.replace(m[0], '');
136             } else { 
137                 s = s.replace(m[0], '{xtpl'+ id + '}');
138             }
139             ++id;
140         }
141         for(var i = tpls.length-1; i >= 0; --i){
142             this.compileTpl(tpls[i]);
143         }
144         this.master = tpls[tpls.length-1];
145         this.tpls = tpls;
146         return this;
147     },
148     /**
149      * same as applyTemplate, except it's done to one of the subTemplates
150      * @param {Number} id of the template
151      * @param {Object} values to apply to template
152      * @param {Object} parent (normaly the instance of this object)
153      */
154     applySubTemplate : function(id, values, parent)
155     {
156         var t = this.tpls[id];
157         try { 
158             if(t.test && !t.test.call(this, values, parent)){
159                 return '';
160             }
161         } catch(e) {
162             Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
163             Roo.log(e.toString());
164             Roo.log(t.test);
165             return ''
166         }
167         try { 
168             
169             if(t.exec && t.exec.call(this, values, parent)){
170                 return '';
171             }
172         } catch(e) {
173             Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
174             Roo.log(e.toString());
175             Roo.log(t.exec);
176             return ''
177         }
178         try {
179             var vs = t.target ? t.target.call(this, values, parent) : values;
180             parent = t.target ? values : parent;
181             if(t.target && vs instanceof Array){
182                 var buf = [];
183                 for(var i = 0, len = vs.length; i < len; i++){
184                     buf[buf.length] = t.compiled.call(this, vs[i], parent);
185                 }
186                 return buf.join('');
187             }
188             return t.compiled.call(this, vs, parent);
189         } catch (e) {
190             Roo.log("Xtemplate.applySubTemplate : Exception thrown");
191             Roo.log(e.toString());
192             Roo.log(t.compiled);
193             return '';
194         }
195     },
196
197     compileTpl : function(tpl)
198     {
199         var fm = Roo.util.Format;
200         var useF = this.disableFormats !== true;
201         var sep = Roo.isGecko ? "+" : ",";
202         var undef = function(str) {
203             Roo.log("Property not found :"  + str);
204             return '';
205         };
206         
207         var fn = function(m, name, format, args)
208         {
209             //Roo.log(arguments);
210             args = args ? args.replace(/\\'/g,"'") : args;
211             //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
212             if (typeof(format) == 'undefined') {
213                 format= 'htmlEncode';
214             }
215             if (format == 'raw' ) {
216                 format = false;
217             }
218             
219             if(name.substr(0, 4) == 'xtpl'){
220                 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
221             }
222             
223             // build an array of options to determine if value is undefined..
224             
225             // basically get 'xxxx.yyyy' then do
226             // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
227             //    (function () { Roo.log("Property not found"); return ''; })() :
228             //    ......
229             
230             var udef_ar = [];
231             var lookfor = '';
232             Roo.each(name.split('.'), function(st) {
233                 lookfor += (lookfor.length ? '.': '') + st;
234                 udef_ar.push(  "(typeof(" + lookfor + ") == 'undefined')"  );
235             });
236             
237             var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
238             
239             
240             if(format && useF){
241                 
242                 args = args ? ',' + args : "";
243                  
244                 if(format.substr(0, 5) != "this."){
245                     format = "fm." + format + '(';
246                 }else{
247                     format = 'this.call("'+ format.substr(5) + '", ';
248                     args = ", values";
249                 }
250                 
251                 return "'"+ sep +   udef_st   +    format + name + args + "))"+sep+"'";
252             }
253              
254             if (args.length) {
255                 // called with xxyx.yuu:(test,test)
256                 // change to ()
257                 return "'"+ sep + udef_st  + name + '(' +  args + "))"+sep+"'";
258             }
259             // raw.. - :raw modifier..
260             return "'"+ sep + udef_st  + name + ")"+sep+"'";
261             
262         };
263         var body;
264         // branched to use + in gecko and [].join() in others
265         if(Roo.isGecko){
266             body = "tpl.compiled = function(values, parent){  with(values) { return '" +
267                    tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
268                     "';};};";
269         }else{
270             body = ["tpl.compiled = function(values, parent){  with (values) { return ['"];
271             body.push(tpl.body.replace(/(\r\n|\n)/g,
272                             '\\n').replace(/'/g, "\\'").replace(this.re, fn));
273             body.push("'].join('');};};");
274             body = body.join('');
275         }
276         
277         Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
278        
279         /** eval:var:zzzzzzz */
280         eval(body);
281         
282         return this;
283     },
284
285     applyTemplate : function(values){
286         return this.master.compiled.call(this, values, {});
287         //var s = this.subs;
288     },
289
290     apply : function(){
291         return this.applyTemplate.apply(this, arguments);
292     }
293
294  });
295
296 Roo.XTemplate.from = function(el){
297     el = Roo.getDom(el);
298     return new Roo.XTemplate(el.value || el.innerHTML);
299 };