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