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