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