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