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