Roo/XTemplate.js
[roojs1] / Roo / XTemplate.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11
12
13 /**
14  * @class Roo.XTemplate
15  * @extends Roo.Template
16  * Provides a template that can have nested templates for loops or conditionals. The syntax is:
17 <pre><code>
18 var t = new Roo.XTemplate(
19         '&lt;select name="{name}"&gt;',
20                 '&lt;tpl for="options"&gt;&lt;option value="{value:trim}"&gt;{text:ellipsis(10)}&lt;/option&gt;&lt;/tpl&gt;',
21         '&lt;/select&gt;'
22 );
23  
24 // then append, applying the master template values
25  </code></pre>
26  *
27  * Supported features:
28  *
29  *  Tags:
30  *    {a_variable} - output encoded.
31  *    {a_variable.format:("Y-m-d")} - call a method on the variable
32  *    {a_variable:raw} - unencoded output
33  *    {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
34  *    {a_variable:this.method_on_template(...)} - call a method on the template object.
35  *  
36  *  Tpl:
37  *      &lt;tpl for="a_variable or condition.."&gt;&lt;/tpl&gt;
38  *      &lt;tpl if="a_variable or condition"&gt;&lt;/tpl&gt;
39  *      &lt;tpl exec="some javascript"&gt;&lt;/tpl&gt;
40  *
41  *      &lt;tpl for="."&gt;&lt;/tpl&gt; - just iterate the property..
42  *      &lt;tpl for=".."&gt;&lt;/tpl&gt; - iterates with the parent (probably the template) 
43  *      
44  *      
45  */
46 Roo.XTemplate = function()
47 {
48     Roo.XTemplate.superclass.constructor.apply(this, arguments);
49     if (this.html) {
50         this.compile();
51     }
52 };
53
54
55 Roo.extend(Roo.XTemplate, Roo.Template, {
56
57     /**
58      *
59      * basic tag replacing syntax
60      * WORD:WORD()
61      *
62      * // you can fake an object call by doing this
63      *  x.t:(test,tesT) 
64      * 
65      */
66     re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
67
68     
69     compile: function()
70     {
71         var s = this.html;
72      
73         s = ['<tpl>', s, '</tpl>'].join('');
74     
75         var re     = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
76             nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
77             ifRe   = /^<tpl\b[^>]*?if="(.*?)"/,
78             execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
79             namedRe = /^<tpl\b[^>]*?name="(\w+)"/,  // named templates..
80             m,
81             id     = 0,
82             tpls   = [];
83     
84         while(true == !!(m = s.match(re))){
85             var forMatch   = m[0].match(nameRe),
86                 ifMatch   = m[0].match(ifRe),
87                 m4   = m[0].match(execRe),
88                 namedMatch   = m[0].match(namedRe),
89                 
90                 exp  = null, 
91                 fn   = null,
92                 exec = null,
93                 name = forMatch && forMatch[1] ? forMatch[1] : '';
94                 
95             if (ifMatch) {
96                 // if - puts fn into test..
97                 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
98                 if(exp){
99                    fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
100                 }
101             }
102             if (m4) {
103                 // exec - calls a function... returns empty if true is  returned.
104                 exp = m4 && m4[1] ? m4[1] : null;
105                 if(exp){
106                    exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
107                 }
108             }
109             if (name) {
110                 // for = 
111                 switch(name){
112                     case '.':  name = new Function('values', 'parent', 'with(values){ return values; }'); break;
113                     case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
114                     default:   name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
115                 }
116             }
117             tpls.push({
118                 id:     id,
119                 target: name,
120                 exec:   exec,
121                 test:   fn,
122                 body:   m[1] || ''
123             });
124             s = s.replace(m[0], '{xtpl'+ id + '}');
125             ++id;
126         }
127         for(var i = tpls.length-1; i >= 0; --i){
128             this.compileTpl(tpls[i]);
129         }
130         this.master = tpls[tpls.length-1];
131         this.tpls = tpls;
132         return this;
133     },
134     /**
135      * same as applyTemplate, except it's done to one of the subTemplates
136      * @param {Number} id of the template
137      * @param {Object} values to apply to template
138      * @param {Object} parent (normaly the instance of this object)
139      */
140     applySubTemplate : function(id, values, parent)
141     {
142         var t = this.tpls[id];
143         try { 
144             if(t.test && !t.test.call(this, values, parent)){
145                 return '';
146             }
147         } catch(e) {
148             Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
149             Roo.log(e.toString());
150             Roo.log(t.test);
151             return ''
152         }
153         try { 
154             
155             if(t.exec && t.exec.call(this, values, parent)){
156                 return '';
157             }
158         } catch(e) {
159             Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
160             Roo.log(e.toString());
161             Roo.log(t.exec);
162             return ''
163         }
164         try {
165             var vs = t.target ? t.target.call(this, values, parent) : values;
166             parent = t.target ? values : parent;
167             if(t.target && vs instanceof Array){
168                 var buf = [];
169                 for(var i = 0, len = vs.length; i < len; i++){
170                     buf[buf.length] = t.compiled.call(this, vs[i], parent);
171                 }
172                 return buf.join('');
173             }
174             return t.compiled.call(this, vs, parent);
175         } catch (e) {
176             Roo.log("Xtemplate.applySubTemplate : Exception thrown");
177             Roo.log(e.toString());
178             Roo.log(t.compiled);
179             return '';
180         }
181     },
182
183     compileTpl : function(tpl)
184     {
185         var fm = Roo.util.Format;
186         var useF = this.disableFormats !== true;
187         var sep = Roo.isGecko ? "+" : ",";
188         var undef = function(str) {
189             Roo.log("Property not found :"  + str);
190             return '';
191         };
192         
193         var fn = function(m, name, format, args)
194         {
195             //Roo.log(arguments);
196             args = args ? args.replace(/\\'/g,"'") : args;
197             //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
198             if (typeof(format) == 'undefined') {
199                 format= 'htmlEncode';
200             }
201             if (format == 'raw' ) {
202                 format = false;
203             }
204             
205             if(name.substr(0, 4) == 'xtpl'){
206                 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
207             }
208             
209             // build an array of options to determine if value is undefined..
210             
211             // basically get 'xxxx.yyyy' then do
212             // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
213             //    (function () { Roo.log("Property not found"); return ''; })() :
214             //    ......
215             
216             var udef_ar = [];
217             var lookfor = '';
218             Roo.each(name.split('.'), function(st) {
219                 lookfor += (lookfor.length ? '.': '') + st;
220                 udef_ar.push(  "(typeof(" + lookfor + ") == 'undefined')"  );
221             });
222             
223             var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
224             
225             
226             if(format && useF){
227                 
228                 args = args ? ',' + args : "";
229                  
230                 if(format.substr(0, 5) != "this."){
231                     format = "fm." + format + '(';
232                 }else{
233                     format = 'this.call("'+ format.substr(5) + '", ';
234                     args = ", values";
235                 }
236                 
237                 return "'"+ sep +   udef_st   +    format + name + args + "))"+sep+"'";
238             }
239              
240             if (args.length) {
241                 // called with xxyx.yuu:(test,test)
242                 // change to ()
243                 return "'"+ sep + udef_st  + name + '(' +  args + "))"+sep+"'";
244             }
245             // raw.. - :raw modifier..
246             return "'"+ sep + udef_st  + name + ")"+sep+"'";
247             
248         };
249         var body;
250         // branched to use + in gecko and [].join() in others
251         if(Roo.isGecko){
252             body = "tpl.compiled = function(values, parent){  with(values) { return '" +
253                    tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
254                     "';};};";
255         }else{
256             body = ["tpl.compiled = function(values, parent){  with (values) { return ['"];
257             body.push(tpl.body.replace(/(\r\n|\n)/g,
258                             '\\n').replace(/'/g, "\\'").replace(this.re, fn));
259             body.push("'].join('');};};");
260             body = body.join('');
261         }
262         
263         Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
264        
265         /** eval:var:zzzzzzz */
266         eval(body);
267         
268         return this;
269     },
270
271     applyTemplate : function(values){
272         return this.master.compiled.call(this, values, {});
273         //var s = this.subs;
274     },
275
276     apply : function(){
277         return this.applyTemplate.apply(this, arguments);
278     }
279
280  });
281
282 Roo.XTemplate.from = function(el){
283     el = Roo.getDom(el);
284     return new Roo.XTemplate(el.value || el.innerHTML);
285 };