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