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