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