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