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