Roo/Template.js
[roojs1] / Roo / Template.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 * @class Roo.Template
14 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
15 * For a list of available format functions, see {@link Roo.util.Format}.<br />
16 * Usage:
17 <pre><code>
18 var t = new Roo.Template({
19     html :  '&lt;div name="{id}"&gt;' + 
20         '&lt;span class="{cls}"&gt;{name:trim} {someval:this.myformat}{value:ellipsis(10)}&lt;/span&gt;' +
21         '&lt;/div&gt;',
22     myformat: function (value, allValues) {
23         return 'XX' + value;
24     }
25 });
26 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
27 </code></pre>
28 * For more information see this blog post with examples: <a href="http://www.jackslocum.com/yui/2006/10/06/domhelper-create-elements-using-dom-html-fragments-or-templates/">DomHelper - Create Elements using DOM, HTML fragments and Templates</a>. 
29 * @constructor
30 * @param {Object} cfg - Configuration object.
31 */
32 Roo.Template = function(cfg){
33     // BC!
34     if(cfg instanceof Array){
35         cfg = cfg.join("");
36     }else if(arguments.length > 1){
37         cfg = Array.prototype.join.call(arguments, "");
38     }
39     
40     
41     if (typeof(cfg) == 'object') {
42         Roo.apply(this,cfg)
43     } else {
44         // bc
45         this.html = cfg;
46     }
47     
48     
49 };
50 Roo.Template.prototype = {
51     
52     /**
53      * @cfg {String} html  The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
54      */
55     html : '',
56     /**
57      * Returns an HTML fragment of this template with the specified values applied.
58      * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
59      * @return {String} The HTML fragment
60      */
61     applyTemplate : function(values){
62         try {
63             
64             if(this.compiled){
65                 return this.compiled(values);
66             }
67             var useF = this.disableFormats !== true;
68             var fm = Roo.util.Format, tpl = this;
69             var fn = function(m, name, format, args){
70                 if(format && useF){
71                     if(format.substr(0, 5) == "this."){
72                         return tpl.call(format.substr(5), values[name], values);
73                     }else{
74                         if(args){
75                             // quoted values are required for strings in compiled templates, 
76                             // but for non compiled we need to strip them
77                             // quoted reversed for jsmin
78                             var re = /^\s*['"](.*)["']\s*$/;
79                             args = args.split(',');
80                             for(var i = 0, len = args.length; i < len; i++){
81                                 args[i] = args[i].replace(re, "$1");
82                             }
83                             args = [values[name]].concat(args);
84                         }else{
85                             args = [values[name]];
86                         }
87                         return fm[format].apply(fm, args);
88                     }
89                 }else{
90                     return values[name] !== undefined ? values[name] : "";
91                 }
92             };
93             return this.html.replace(this.re, fn);
94         } catch (e) {
95             Roo.log(e);
96             throw e;
97         }
98          
99     },
100     
101     loading : false,
102     
103     load : function (url, success)
104     {
105         if (this.loading) {
106             return;
107         }
108         this.loading = true;
109         var _t = this;
110         var cx = new Roo.data.Connection();
111         cx.request({
112             url : url,
113             method : 'GET',
114             success : function (response) {
115                 _t.loading = false;
116                 _t.html = response.responseText;
117                 success && success();
118             },
119             failure : function(response) {
120                 Roo.log("Template failed to load from " + url);
121                 _t.loading = false;
122             }
123         });
124     },
125
126     /**
127      * Sets the HTML used as the template and optionally compiles it.
128      * @param {String} html
129      * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
130      * @return {Roo.Template} this
131      */
132     set : function(html, compile){
133         this.html = html;
134         this.compiled = null;
135         if(compile){
136             this.compile();
137         }
138         return this;
139     },
140     
141     /**
142      * True to disable format functions (defaults to false)
143      * @type Boolean
144      */
145     disableFormats : false,
146     
147     /**
148     * The regular expression used to match template variables 
149     * @type RegExp
150     * @property 
151     */
152     re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
153     
154     /**
155      * Compiles the template into an internal function, eliminating the RegEx overhead.
156      * @return {Roo.Template} this
157      */
158     compile : function(){
159         var fm = Roo.util.Format;
160         var useF = this.disableFormats !== true;
161         var sep = Roo.isGecko ? "+" : ",";
162         var fn = function(m, name, format, args){
163             if(format && useF){
164                 args = args ? ',' + args : "";
165                 if(format.substr(0, 5) != "this."){
166                     format = "fm." + format + '(';
167                 }else{
168                     format = 'this.call("'+ format.substr(5) + '", ';
169                     args = ", values";
170                 }
171             }else{
172                 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
173             }
174             return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
175         };
176         var body;
177         // branched to use + in gecko and [].join() in others
178         if(Roo.isGecko){
179             body = "this.compiled = function(values){ return '" +
180                    this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
181                     "';};";
182         }else{
183             body = ["this.compiled = function(values){ return ['"];
184             body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
185             body.push("'].join('');};");
186             body = body.join('');
187         }
188         /**
189          * eval:var:values
190          * eval:var:fm
191          */
192         eval(body);
193         return this;
194     },
195     
196     // private function used to call members
197     call : function(fnName, value, allValues){
198         return this[fnName](value, allValues);
199     },
200     
201     /**
202      * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
203      * @param {String/HTMLElement/Roo.Element} el The context element
204      * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
205      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
206      * @return {HTMLElement/Roo.Element} The new node or Element
207      */
208     insertFirst: function(el, values, returnElement){
209         return this.doInsert('afterBegin', el, values, returnElement);
210     },
211
212     /**
213      * Applies the supplied values to the template and inserts the new node(s) before el.
214      * @param {String/HTMLElement/Roo.Element} el The context element
215      * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
216      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
217      * @return {HTMLElement/Roo.Element} The new node or Element
218      */
219     insertBefore: function(el, values, returnElement){
220         return this.doInsert('beforeBegin', el, values, returnElement);
221     },
222
223     /**
224      * Applies the supplied values to the template and inserts the new node(s) after el.
225      * @param {String/HTMLElement/Roo.Element} el The context element
226      * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
227      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
228      * @return {HTMLElement/Roo.Element} The new node or Element
229      */
230     insertAfter : function(el, values, returnElement){
231         return this.doInsert('afterEnd', el, values, returnElement);
232     },
233     
234     /**
235      * Applies the supplied values to the template and appends the new node(s) to el.
236      * @param {String/HTMLElement/Roo.Element} el The context element
237      * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
238      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
239      * @return {HTMLElement/Roo.Element} The new node or Element
240      */
241     append : function(el, values, returnElement){
242         return this.doInsert('beforeEnd', el, values, returnElement);
243     },
244
245     doInsert : function(where, el, values, returnEl){
246         el = Roo.getDom(el);
247         var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
248         return returnEl ? Roo.get(newNode, true) : newNode;
249     },
250
251     /**
252      * Applies the supplied values to the template and overwrites the content of el with the new node(s).
253      * @param {String/HTMLElement/Roo.Element} el The context element
254      * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
255      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
256      * @return {HTMLElement/Roo.Element} The new node or Element
257      */
258     overwrite : function(el, values, returnElement){
259         el = Roo.getDom(el);
260         el.innerHTML = this.applyTemplate(values);
261         return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
262     }
263 };
264 /**
265  * Alias for {@link #applyTemplate}
266  * @method
267  */
268 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
269
270 // backwards compat
271 Roo.DomHelper.Template = Roo.Template;
272
273 /**
274  * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
275  * @param {String/HTMLElement} el A DOM element or its id
276  * @returns {Roo.Template} The created template
277  * @static
278  */
279 Roo.Template.from = function(el){
280     el = Roo.getDom(el);
281     return new Roo.Template(el.value || el.innerHTML);
282 };