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