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