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