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