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