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