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