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