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     afterLoad : false,
104     
105     load : function (url, success)
106     {
107         
108         this.afterLoad = success;
109         if (this.loading) {
110             return;
111         }
112         
113         this.loading = true;
114         this.compiled = false;
115         var _t = this;
116         var cx = new Roo.data.Connection();
117         cx.request({
118             url : url,
119             method : 'GET',
120             success : function (response) {
121                 _t.loading = false;
122                 _t.html = response.responseText;
123                 _t.afterLoad && _t.afterLoad();
124             },
125             failure : function(response) {
126                 Roo.log("Template failed to load from " + url);
127                 _t.loading = false;
128             }
129         });
130     },
131
132     /**
133      * Sets the HTML used as the template and optionally compiles it.
134      * @param {String} html
135      * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
136      * @return {Roo.Template} this
137      */
138     set : function(html, compile){
139         this.html = html;
140         this.compiled = null;
141         if(compile){
142             this.compile();
143         }
144         return this;
145     },
146     
147     /**
148      * True to disable format functions (defaults to false)
149      * @type Boolean
150      */
151     disableFormats : false,
152     
153     /**
154     * The regular expression used to match template variables 
155     * @type RegExp
156     * @property 
157     */
158     re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
159     
160     /**
161      * Compiles the template into an internal function, eliminating the RegEx overhead.
162      * @return {Roo.Template} this
163      */
164     compile : function(){
165         var fm = Roo.util.Format;
166         var useF = this.disableFormats !== true;
167         var sep = Roo.isGecko ? "+" : ",";
168         var fn = function(m, name, format, args){
169             if(format && useF){
170                 args = args ? ',' + args : "";
171                 if(format.substr(0, 5) != "this."){
172                     format = "fm." + format + '(';
173                 }else{
174                     format = 'this.call("'+ format.substr(5) + '", ';
175                     args = ", values";
176                 }
177             }else{
178                 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
179             }
180             return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
181         };
182         var body;
183         // branched to use + in gecko and [].join() in others
184         if(Roo.isGecko){
185             body = "this.compiled = function(values){ return '" +
186                    this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
187                     "';};";
188         }else{
189             body = ["this.compiled = function(values){ return ['"];
190             body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
191             body.push("'].join('');};");
192             body = body.join('');
193         }
194         /**
195          * eval:var:values
196          * eval:var:fm
197          */
198         eval(body);
199         return this;
200     },
201     
202     // private function used to call members
203     call : function(fnName, value, allValues){
204         return this[fnName](value, allValues);
205     },
206     
207     /**
208      * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
209      * @param {String/HTMLElement/Roo.Element} el The context element
210      * @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'})
211      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
212      * @return {HTMLElement/Roo.Element} The new node or Element
213      */
214     insertFirst: function(el, values, returnElement){
215         return this.doInsert('afterBegin', el, values, returnElement);
216     },
217
218     /**
219      * Applies the supplied values to the template and inserts the new node(s) before el.
220      * @param {String/HTMLElement/Roo.Element} el The context element
221      * @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'})
222      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
223      * @return {HTMLElement/Roo.Element} The new node or Element
224      */
225     insertBefore: function(el, values, returnElement){
226         return this.doInsert('beforeBegin', el, values, returnElement);
227     },
228
229     /**
230      * Applies the supplied values to the template and inserts the new node(s) after el.
231      * @param {String/HTMLElement/Roo.Element} el The context element
232      * @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'})
233      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
234      * @return {HTMLElement/Roo.Element} The new node or Element
235      */
236     insertAfter : function(el, values, returnElement){
237         return this.doInsert('afterEnd', el, values, returnElement);
238     },
239     
240     /**
241      * Applies the supplied values to the template and appends the new node(s) to el.
242      * @param {String/HTMLElement/Roo.Element} el The context element
243      * @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'})
244      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
245      * @return {HTMLElement/Roo.Element} The new node or Element
246      */
247     append : function(el, values, returnElement){
248         return this.doInsert('beforeEnd', el, values, returnElement);
249     },
250
251     doInsert : function(where, el, values, returnEl){
252         el = Roo.getDom(el);
253         var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
254         return returnEl ? Roo.get(newNode, true) : newNode;
255     },
256
257     /**
258      * Applies the supplied values to the template and overwrites the content of el with the new node(s).
259      * @param {String/HTMLElement/Roo.Element} el The context element
260      * @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'})
261      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
262      * @return {HTMLElement/Roo.Element} The new node or Element
263      */
264     overwrite : function(el, values, returnElement){
265         el = Roo.getDom(el);
266         el.innerHTML = this.applyTemplate(values);
267         return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
268     }
269 };
270 /**
271  * Alias for {@link #applyTemplate}
272  * @method
273  */
274 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
275
276 // backwards compat
277 Roo.DomHelper.Template = Roo.Template;
278
279 /**
280  * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
281  * @param {String/HTMLElement} el A DOM element or its id
282  * @returns {Roo.Template} The created template
283  * @static
284  */
285 Roo.Template.from = function(el){
286     el = Roo.getDom(el);
287     return new Roo.Template(el.value || el.innerHTML);
288 };