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