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