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