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