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;/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         
103         var div = document.createElement('div');
104         div.innerHTML =   this.html  ;
105         
106         this.tpls = [];
107         var _t = this;
108         this.iterChild(div, function(n) {_t.compileNode(n, true); });
109         
110         var tpls = this.tpls;
111         
112         // create a top level template from the snippet..
113         
114         //Roo.log(div.innerHTML);
115         
116         var tpl = {
117             uid : 'master',
118             id : this.id++,
119             attr : false,
120             value : false,
121             body : div.innerHTML,
122             
123             forCall : false,
124             execCall : false,
125             dom : div,
126             isTop : true
127             
128         };
129         tpls.unshift(tpl);
130         
131         
132         // compile them...
133         this.tpls = [];
134         Roo.each(tpls, function(tp){
135             this.compileTpl(tp);
136             this.tpls[tp.id] = tp;
137         }, this);
138         
139         this.master = tpls[0];
140         return this;
141         
142         
143     },
144     
145     compileNode : function(node, istop) {
146         // test for
147         //Roo.log(node);
148         
149         
150         // skip anything not a tag..
151         if (node.nodeType != 1) {
152             if (node.nodeType == 3 && !this.inPre) {
153                 // reduce white space..
154                 node.nodeValue = node.nodeValue.replace(/\s+/g, ' '); 
155                 
156             }
157             return;
158         }
159         
160         var tpl = {
161             uid : false,
162             id : false,
163             attr : false,
164             value : false,
165             body : '',
166             
167             forCall : false,
168             execCall : false,
169             dom : false,
170             isTop : istop
171             
172             
173         };
174         
175         
176         switch(true) {
177             case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
178             case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
179             case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
180             case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
181             // no default..
182         }
183         
184         
185         if (!tpl.attr) {
186             // just itterate children..
187             this.iterChild(node,this.compileNode);
188             return;
189         }
190         tpl.uid = this.id++;
191         tpl.value = node.getAttribute('roo-' +  tpl.attr);
192         node.removeAttribute('roo-'+ tpl.attr);
193         if (tpl.attr != 'name') {
194             var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
195             node.parentNode.replaceChild(placeholder,  node);
196         } else {
197             
198             var placeholder =  document.createElement('span');
199             placeholder.className = 'roo-tpl-' + tpl.value;
200             node.parentNode.replaceChild(placeholder,  node);
201         }
202         
203         // parent now sees '{domtplXXXX}
204         this.iterChild(node,this.compileNode);
205         
206         // we should now have node body...
207         var div = document.createElement('div');
208         div.appendChild(node);
209         tpl.dom = node;
210         // this has the unfortunate side effect of converting tagged attributes
211         // eg. href="{...}" into %7C...%7D
212         // this has been fixed by searching for those combo's although it's a bit hacky..
213         
214         
215         tpl.body = div.innerHTML;
216         
217         
218          
219         tpl.id = tpl.uid;
220         switch(tpl.attr) {
221             case 'for' :
222                 switch (tpl.value) {
223                     case '.':  tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
224                     case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
225                     default:   tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
226                 }
227                 break;
228             
229             case 'exec':
230                 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
231                 break;
232             
233             case 'if':     
234                 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
235                 break;
236             
237             case 'name':
238                 tpl.id  = tpl.value; // replace non characters???
239                 break;
240             
241         }
242         
243         
244         this.tpls.push(tpl);
245         
246         
247         
248     },
249     
250     
251     
252     
253     /**
254      * Compile a segment of the template into a 'sub-template'
255      *
256      * 
257      * 
258      *
259      */
260     compileTpl : function(tpl)
261     {
262         var fm = Roo.util.Format;
263         var useF = this.disableFormats !== true;
264         
265         var sep = Roo.isGecko ? "+\n" : ",\n";
266         
267         var undef = function(str) {
268             Roo.debug && Roo.log("Property not found :"  + str);
269             return '';
270         };
271           
272         //Roo.log(tpl.body);
273         
274         
275         
276         var fn = function(m, lbrace, name, format, args)
277         {
278             //Roo.log("ARGS");
279             //Roo.log(arguments);
280             args = args ? args.replace(/\\'/g,"'") : args;
281             //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
282             if (typeof(format) == 'undefined') {
283                 format =  'htmlEncode'; 
284             }
285             if (format == 'raw' ) {
286                 format = false;
287             }
288             
289             if(name.substr(0, 6) == 'domtpl'){
290                 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
291             }
292             
293             // build an array of options to determine if value is undefined..
294             
295             // basically get 'xxxx.yyyy' then do
296             // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
297             //    (function () { Roo.log("Property not found"); return ''; })() :
298             //    ......
299             
300             var udef_ar = [];
301             var lookfor = '';
302             Roo.each(name.split('.'), function(st) {
303                 lookfor += (lookfor.length ? '.': '') + st;
304                 udef_ar.push(  "(typeof(" + lookfor + ") == 'undefined')"  );
305             });
306             
307             var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
308             
309             
310             if(format && useF){
311                 
312                 args = args ? ',' + args : "";
313                  
314                 if(format.substr(0, 5) != "this."){
315                     format = "fm." + format + '(';
316                 }else{
317                     format = 'this.call("'+ format.substr(5) + '", ';
318                     args = ", values";
319                 }
320                 
321                 return "'"+ sep +   udef_st   +    format + name + args + "))"+sep+"'";
322             }
323              
324             if (args.length) {
325                 // called with xxyx.yuu:(test,test)
326                 // change to ()
327                 return "'"+ sep + udef_st  + name + '(' +  args + "))"+sep+"'";
328             }
329             // raw.. - :raw modifier..
330             return "'"+ sep + udef_st  + name + ")"+sep+"'";
331             
332         };
333         var body;
334         // branched to use + in gecko and [].join() in others
335         if(Roo.isGecko){
336             body = "tpl.compiled = function(values, parent){  with(values) { return '" +
337                    tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
338                     "';};};";
339         }else{
340             body = ["tpl.compiled = function(values, parent){  with (values) { return ['"];
341             body.push(tpl.body.replace(/(\r\n|\n)/g,
342                             '\\n').replace(/'/g, "\\'").replace(this.re, fn));
343             body.push("'].join('');};};");
344             body = body.join('');
345         }
346         
347         Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
348        
349         /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef  */
350         eval(body);
351         
352         return this;
353     },
354      
355     /**
356      * same as applyTemplate, except it's done to one of the subTemplates
357      * when using named templates, you can do:
358      *
359      * var str = pl.applySubTemplate('your-name', values);
360      *
361      * 
362      * @param {Number} id of the template
363      * @param {Object} values to apply to template
364      * @param {Object} parent (normaly the instance of this object)
365      */
366     applySubTemplate : function(id, values, parent)
367     {
368         
369         
370         var t = this.tpls[id];
371         
372         
373         try { 
374             if(t.ifCall && !t.ifCall.call(this, values, parent)){
375                 Roo.log('if call on ' + t.value + ' return false');
376                 return '';
377             }
378         } catch(e) {
379             Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
380             Roo.log(values);
381           
382             return '';
383         }
384         try { 
385             
386             if(t.execCall && t.execCall.call(this, values, parent)){
387                 return '';
388             }
389         } catch(e) {
390             Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
391             Roo.log(values);
392             return '';
393         }
394         
395         try {
396             var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
397             parent = t.target ? values : parent;
398             if(t.forCall && vs instanceof Array){
399                 var buf = [];
400                 for(var i = 0, len = vs.length; i < len; i++){
401                     try {
402                         buf[buf.length] = t.compiled.call(this, vs[i], parent);
403                     } catch (e) {
404                         Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
405                         Roo.log(e.body);
406                         //Roo.log(t.compiled);
407                         Roo.log(vs[i]);
408                     }   
409                 }
410                 return buf.join('');
411             }
412         } catch (e) {
413             Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
414             Roo.log(values);
415             return '';
416         }
417         try {
418             return t.compiled.call(this, vs, parent);
419         } catch (e) {
420             Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
421             Roo.log(e.body);
422             //Roo.log(t.compiled);
423             Roo.log(values);
424             return '';
425         }
426     },
427
428    
429
430     applyTemplate : function(values){
431         return this.master.compiled.call(this, values, {});
432         //var s = this.subs;
433     },
434
435     apply : function(){
436         return this.applyTemplate.apply(this, arguments);
437     }
438
439  });
440
441 Roo.DomTemplate.from = function(el){
442     el = Roo.getDom(el);
443     return new Roo.Domtemplate(el.value || el.innerHTML);
444 };