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