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