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