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