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