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