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