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.MasterTemplate(
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  *      <tpl for="a_variable or condition.."></tpl>
38  *      <tpl if="a_variable or condition"></tpl>
39  *      <tpl exec="some javascript"></tpl>
40  *
41  */
42 Roo.XTemplate = function()
43 {
44     Roo.XTemplate.superclass.constructor.apply(this, arguments);
45     if (this.html) {
46         this.compile();
47     }
48 };
49
50
51 Roo.extend(Roo.XTemplate, Roo.Template, {
52
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: function()
66     {
67         var s = this.html;
68      
69         s = ['<tpl>', s, '</tpl>'].join('');
70     
71         var re     = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
72             nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
73             ifRe   = /^<tpl\b[^>]*?if="(.*?)"/,
74             execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
75             m,
76             id     = 0,
77             tpls   = [];
78     
79         while(true == !!(m = s.match(re))){
80             var m2   = m[0].match(nameRe),
81                 m3   = m[0].match(ifRe),
82                 m4   = m[0].match(execRe),
83                 exp  = null, 
84                 fn   = null,
85                 exec = null,
86                 name = m2 && m2[1] ? m2[1] : '';
87                 
88             if (m3) {
89                 // if - puts fn into test..
90                 exp = m3 && m3[1] ? m3[1] : null;
91                 if(exp){
92                    fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
93                 }
94             }
95             if (m4) {
96                 // exec - calls a function... returns empty if true is  returned.
97                 exp = m4 && m4[1] ? m4[1] : null;
98                 if(exp){
99                    exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
100                 }
101             }
102             if (name) {
103                 // for = 
104                 switch(name){
105                     case '.':  name = new Function('values', 'parent', 'with(values){ return values; }'); break;
106                     case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
107                     default:   name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
108                 }
109             }
110             tpls.push({
111                 id:     id,
112                 target: name,
113                 exec:   exec,
114                 test:   fn,
115                 body:   m[1] || ''
116             });
117             s = s.replace(m[0], '{xtpl'+ id + '}');
118             ++id;
119         }
120         for(var i = tpls.length-1; i >= 0; --i){
121             this.compileTpl(tpls[i]);
122         }
123         this.master = tpls[tpls.length-1];
124         this.tpls = tpls;
125         return this;
126     },
127     
128     applySubTemplate : function(id, values, parent)
129     {
130         var t = this.tpls[id];
131         if(t.test && !t.test.call(this, values, parent)){
132             return '';
133         }
134         if(t.exec && t.exec.call(this, values, parent)){
135             return '';
136         }
137         var vs = t.target ? t.target.call(this, values, parent) : values;
138         parent = t.target ? values : parent;
139         if(t.target && vs instanceof Array){
140             var buf = [];
141             for(var i = 0, len = vs.length; i < len; i++){
142                 buf[buf.length] = t.compiled.call(this, vs[i], parent);
143             }
144             return buf.join('');
145         }
146         return t.compiled.call(this, vs, parent);
147     },
148
149     compileTpl : function(tpl)
150     {
151         var fm = Roo.util.Format;
152         var useF = this.disableFormats !== true;
153         var sep = Roo.isGecko ? "+" : ",";
154         var fn = function(m, name, format, args){
155             //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
156             if (typeof(format) == 'undefined') {
157                 format= 'htmlEncode';
158             }
159             if (format == 'raw' ) {
160                 format = false;
161             }
162             
163             if(name.substr(0, 4) == 'xtpl'){
164                 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
165             }
166             
167             var v;
168             //if(name.indexOf('.') != -1){
169                 v = name;
170             //}else{
171             //    v = "values['" + name + "']";
172             //}
173             if(format && useF){
174                 
175                 args = args ? ',' + args : "";
176                  
177                 if(format.substr(0, 5) != "this."){
178                     format = "fm." + format + '(';
179                 }else{
180                     format = 'this.call("'+ format.substr(5) + '", ';
181                     args = ", values";
182                 }
183                 return "'"+ sep + format + v + args + ")"+sep+"'";
184             }
185              
186             if (args.length) {
187                 // called with xxyx.yuu:(test,test)
188                 // change to ()
189                 return "'"+ sep + "("+v+" === undefined ? '' : " + v + '(' +  args + "))"+sep+"'";
190             }
191             // raw.. - :raw modifier..
192             return "'"+ sep + "("+v+" === undefined ? '' : " + v + ")"+sep+"'";
193             
194         };
195         var body;
196         // branched to use + in gecko and [].join() in others
197         if(Roo.isGecko){
198             body = "tpl.compiled = function(values, parent){ with(values) { return '" +
199                    tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
200                     "';};};";
201         }else{
202             body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
203             body.push(tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
204             body.push("'].join('');};};");
205             body = body.join('');
206         }
207         
208         /** eval:var:zzzzzzz */
209         eval(body);
210         Roo.log(body.replace(/\\n/,'\n'));
211         
212         return this;
213     },
214
215     applyTemplate : function(values){
216         return this.master.compiled.call(this, values, {});
217         //var s = this.subs;
218     },
219
220     apply : function(){
221         return this.applyTemplate.apply(this, arguments);
222     }
223
224  });
225
226 Roo.XTemplate.from = function(el){
227     el = Roo.getDom(el);
228     return new Roo.XTemplate(el.value || el.innerHTML);
229 };