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