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