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