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