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