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