remove debugging code
[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;/div&gt;
31         &lt;div roo-if="a_variable or condition"&gt;&lt;/div&gt;
32         &lt;div roo-exec="some javascript"&gt;&lt;/div&gt;
33         &lt;div roo-name="named_template"&gt;&lt;/div&gt; 
34   
35 </code></pre>
36  *      
37  */
38 Roo.DomTemplate = function()
39 {
40      Roo.DomTemplate.superclass.constructor.apply(this, arguments);
41      if (this.html) {
42         this.compile();
43      }
44 };
45
46
47 Roo.extend(Roo.DomTemplate, Roo.Template, {
48     /**
49      * id counter for sub templates.
50      */
51     id : 0,
52     /**
53      * flag to indicate if dom parser is inside a pre,
54      * it will strip whitespace if not.
55      */
56     inPre : false,
57     
58     /**
59      * The various sub templates
60      */
61     tpls : false,
62     
63     
64     
65     /**
66      *
67      * basic tag replacing syntax
68      * WORD:WORD()
69      *
70      * // you can fake an object call by doing this
71      *  x.t:(test,tesT) 
72      * 
73      */
74     re : /(\{|\%7B)([\w-\.]+)(?:\:([\w\.]*)(?:\(([^)]*?)?\))?)?(\}|\%7D)/g,
75     //re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
76     
77     iterChild : function (node, method) {
78         
79         var oldPre = this.inPre;
80         if (node.tagName == 'PRE') {
81             this.inPre = true;
82         }
83         for( var i = 0; i < node.childNodes.length; i++) {
84             method.call(this, node.childNodes[i]);
85         }
86         this.inPre = oldPre;
87     },
88     
89     
90     
91     /**
92      * compile the template
93      *
94      * This is not recursive, so I'm not sure how nested templates are really going to be handled..
95      *
96      */
97     compile: function()
98     {
99         var s = this.html;
100         
101         // covert the html into DOM...
102         var doc = false;
103         var div =false;
104         try {
105             doc = document.implementation.createHTMLDocument("");
106             doc.documentElement.innerHTML =   this.html  ;
107             div = doc.documentElement;
108         } catch (e) {
109             // old IE... - nasty -- it causes all sorts of issues.. with
110             // images getting pulled from server..
111             div = document.createElement('div');
112             div.innerHTML = this.html;
113         }
114         //doc.documentElement.innerHTML = htmlBody
115          
116         
117         
118         this.tpls = [];
119         var _t = this;
120         this.iterChild(div, function(n) {_t.compileNode(n, true); });
121         
122         var tpls = this.tpls;
123         
124         // create a top level template from the snippet..
125         
126         //Roo.log(div.innerHTML);
127         
128         var tpl = {
129             uid : 'master',
130             id : this.id++,
131             attr : false,
132             value : false,
133             body : div.innerHTML,
134             
135             forCall : false,
136             execCall : false,
137             dom : div,
138             isTop : true
139             
140         };
141         tpls.unshift(tpl);
142         
143         
144         // compile them...
145         this.tpls = [];
146         Roo.each(tpls, function(tp){
147             this.compileTpl(tp);
148             this.tpls[tp.id] = tp;
149         }, this);
150         
151         this.master = tpls[0];
152         return this;
153         
154         
155     },
156     
157     compileNode : function(node, istop) {
158         // test for
159         //Roo.log(node);
160         
161         
162         // skip anything not a tag..
163         if (node.nodeType != 1) {
164             if (node.nodeType == 3 && !this.inPre) {
165                 // reduce white space..
166                 node.nodeValue = node.nodeValue.replace(/\s+/g, ' '); 
167                 
168             }
169             return;
170         }
171         
172         var tpl = {
173             uid : false,
174             id : false,
175             attr : false,
176             value : false,
177             body : '',
178             
179             forCall : false,
180             execCall : false,
181             dom : false,
182             isTop : istop
183             
184             
185         };
186         
187         
188         switch(true) {
189             case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
190             case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
191             case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
192             case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
193             // no default..
194         }
195         
196         
197         if (!tpl.attr) {
198             // just itterate children..
199             this.iterChild(node,this.compileNode);
200             return;
201         }
202         tpl.uid = this.id++;
203         tpl.value = node.getAttribute('roo-' +  tpl.attr);
204         node.removeAttribute('roo-'+ tpl.attr);
205         if (tpl.attr != 'name') {
206             var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
207             node.parentNode.replaceChild(placeholder,  node);
208         } else {
209             
210             var placeholder =  document.createElement('span');
211             placeholder.className = 'roo-tpl-' + tpl.value;
212             node.parentNode.replaceChild(placeholder,  node);
213         }
214         
215         // parent now sees '{domtplXXXX}
216         this.iterChild(node,this.compileNode);
217         
218         // we should now have node body...
219         var div = document.createElement('div');
220         div.appendChild(node);
221         tpl.dom = node;
222         // this has the unfortunate side effect of converting tagged attributes
223         // eg. href="{...}" into %7C...%7D
224         // this has been fixed by searching for those combo's although it's a bit hacky..
225         
226         
227         tpl.body = div.innerHTML;
228         
229         
230          
231         tpl.id = tpl.uid;
232         switch(tpl.attr) {
233             case 'for' :
234                 switch (tpl.value) {
235                     case '.':  tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
236                     case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
237                     default:   tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
238                 }
239                 break;
240             
241             case 'exec':
242                 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
243                 break;
244             
245             case 'if':     
246                 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
247                 break;
248             
249             case 'name':
250                 tpl.id  = tpl.value; // replace non characters???
251                 break;
252             
253         }
254         
255         
256         this.tpls.push(tpl);
257         
258         
259         
260     },
261     
262     
263     
264     
265     /**
266      * Compile a segment of the template into a 'sub-template'
267      *
268      * 
269      * 
270      *
271      */
272     compileTpl : function(tpl)
273     {
274         var fm = Roo.util.Format;
275         var useF = this.disableFormats !== true;
276         
277         var sep = Roo.isGecko ? "+\n" : ",\n";
278         
279         var undef = function(str) {
280             Roo.debug && Roo.log("Property not found :"  + str);
281             return '';
282         };
283           
284         //Roo.log(tpl.body);
285         
286         
287         
288         var fn = function(m, lbrace, name, format, args)
289         {
290             //Roo.log("ARGS");
291             //Roo.log(arguments);
292             args = args ? args.replace(/\\'/g,"'") : args;
293             //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
294             if (typeof(format) == 'undefined') {
295                 format =  'htmlEncode'; 
296             }
297             if (format == 'raw' ) {
298                 format = false;
299             }
300             
301             if(name.substr(0, 6) == 'domtpl'){
302                 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
303             }
304             
305             // build an array of options to determine if value is undefined..
306             
307             // basically get 'xxxx.yyyy' then do
308             // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
309             //    (function () { Roo.log("Property not found"); return ''; })() :
310             //    ......
311             
312             var udef_ar = [];
313             var lookfor = '';
314             Roo.each(name.split('.'), function(st) {
315                 lookfor += (lookfor.length ? '.': '') + st;
316                 udef_ar.push(  "(typeof(" + lookfor + ") == 'undefined')"  );
317             });
318             
319             var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
320             
321             
322             if(format && useF){
323                 
324                 args = args ? ',' + args : "";
325                  
326                 if(format.substr(0, 5) != "this."){
327                     format = "fm." + format + '(';
328                 }else{
329                     format = 'this.call("'+ format.substr(5) + '", ';
330                     args = ", values";
331                 }
332                 
333                 return "'"+ sep +   udef_st   +    format + name + args + "))"+sep+"'";
334             }
335              
336             if (args && args.length) {
337                 // called with xxyx.yuu:(test,test)
338                 // change to ()
339                 return "'"+ sep + udef_st  + name + '(' +  args + "))"+sep+"'";
340             }
341             // raw.. - :raw modifier..
342             return "'"+ sep + udef_st  + name + ")"+sep+"'";
343             
344         };
345         var body;
346         // branched to use + in gecko and [].join() in others
347         if(Roo.isGecko){
348             body = "tpl.compiled = function(values, parent){  with(values) { return '" +
349                    tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
350                     "';};};";
351         }else{
352             body = ["tpl.compiled = function(values, parent){  with (values) { return ['"];
353             body.push(tpl.body.replace(/(\r\n|\n)/g,
354                             '\\n').replace(/'/g, "\\'").replace(this.re, fn));
355             body.push("'].join('');};};");
356             body = body.join('');
357         }
358         
359         Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
360        
361         /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef  */
362         eval(body);
363         
364         return this;
365     },
366      
367     /**
368      * same as applyTemplate, except it's done to one of the subTemplates
369      * when using named templates, you can do:
370      *
371      * var str = pl.applySubTemplate('your-name', values);
372      *
373      * 
374      * @param {Number} id of the template
375      * @param {Object} values to apply to template
376      * @param {Object} parent (normaly the instance of this object)
377      */
378     applySubTemplate : function(id, values, parent)
379     {
380         
381         
382         var t = this.tpls[id];
383         
384         
385         try { 
386             if(t.ifCall && !t.ifCall.call(this, values, parent)){
387                 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
388                 return '';
389             }
390         } catch(e) {
391             Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
392             Roo.log(values);
393           
394             return '';
395         }
396         try { 
397             
398             if(t.execCall && t.execCall.call(this, values, parent)){
399                 return '';
400             }
401         } catch(e) {
402             Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
403             Roo.log(values);
404             return '';
405         }
406         
407         try {
408             var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
409             parent = t.target ? values : parent;
410             if(t.forCall && vs instanceof Array){
411                 var buf = [];
412                 for(var i = 0, len = vs.length; i < len; i++){
413                     try {
414                         buf[buf.length] = t.compiled.call(this, vs[i], parent);
415                     } catch (e) {
416                         Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
417                         Roo.log(e.body);
418                         //Roo.log(t.compiled);
419                         Roo.log(vs[i]);
420                     }   
421                 }
422                 return buf.join('');
423             }
424         } catch (e) {
425             Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
426             Roo.log(values);
427             return '';
428         }
429         try {
430             return t.compiled.call(this, vs, parent);
431         } catch (e) {
432             Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
433             Roo.log(e.body);
434             //Roo.log(t.compiled);
435             Roo.log(values);
436             return '';
437         }
438     },
439
440    
441
442     applyTemplate : function(values){
443         return this.master.compiled.call(this, values, {});
444         //var s = this.subs;
445     },
446
447     apply : function(){
448         return this.applyTemplate.apply(this, arguments);
449     }
450
451  });
452
453 Roo.DomTemplate.from = function(el){
454     el = Roo.getDom(el);
455     return new Roo.Domtemplate(el.value || el.innerHTML);
456 };