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