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