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