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