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