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