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