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 : 
20     '&lt;div name="{id}"&gt;',
21         '&lt;span class="{cls}"&gt;{name:trim} {value:ellipsis(10)}&lt;/span&gt;',
22     '&lt;/div&gt;'
23 );
24 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
25 </code></pre>
26 * 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>. 
27 * @constructor
28 * @param {Object} cfg - Configuration object.
29 * @param {String/Array} html 
30 */
31 Roo.Template = function(cfg){
32     if(cfg instanceof Array){
33         cfg = cfg.join("");
34     }else if(arguments.length > 1){
35         cfg = Array.prototype.join.call(arguments, "");
36     }
37     
38     /**@private*/
39     if (typeof(cfg) == 'object') {
40         Roo.apply(this,cfg)
41     } else {
42         this.html = cfg;
43     }
44     
45     
46 };
47 Roo.Template.prototype = {
48     
49     /**
50      * @cfg {String} html  The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
51      */
52     html : '',
53     /**
54      * Returns an HTML fragment of this template with the specified values applied.
55      * @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'})
56      * @return {String} The HTML fragment
57      */
58     applyTemplate : function(values){
59         try {
60             
61             if(this.compiled){
62                 return this.compiled(values);
63             }
64             var useF = this.disableFormats !== true;
65             var fm = Roo.util.Format, tpl = this;
66             var fn = function(m, name, format, args){
67                 if(format && useF){
68                     if(format.substr(0, 5) == "this."){
69                         return tpl.call(format.substr(5), values[name], values);
70                     }else{
71                         if(args){
72                             // quoted values are required for strings in compiled templates, 
73                             // but for non compiled we need to strip them
74                             // quoted reversed for jsmin
75                             var re = /^\s*['"](.*)["']\s*$/;
76                             args = args.split(',');
77                             for(var i = 0, len = args.length; i < len; i++){
78                                 args[i] = args[i].replace(re, "$1");
79                             }
80                             args = [values[name]].concat(args);
81                         }else{
82                             args = [values[name]];
83                         }
84                         return fm[format].apply(fm, args);
85                     }
86                 }else{
87                     return values[name] !== undefined ? values[name] : "";
88                 }
89             };
90             return this.html.replace(this.re, fn);
91         } catch (e) {
92             Roo.log(e);
93             throw e;
94         }
95          
96     },
97     
98     /**
99      * Sets the HTML used as the template and optionally compiles it.
100      * @param {String} html
101      * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
102      * @return {Roo.Template} this
103      */
104     set : function(html, compile){
105         this.html = html;
106         this.compiled = null;
107         if(compile){
108             this.compile();
109         }
110         return this;
111     },
112     
113     /**
114      * True to disable format functions (defaults to false)
115      * @type Boolean
116      */
117     disableFormats : false,
118     
119     /**
120     * The regular expression used to match template variables 
121     * @type RegExp
122     * @property 
123     */
124     re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
125     
126     /**
127      * Compiles the template into an internal function, eliminating the RegEx overhead.
128      * @return {Roo.Template} this
129      */
130     compile : function(){
131         var fm = Roo.util.Format;
132         var useF = this.disableFormats !== true;
133         var sep = Roo.isGecko ? "+" : ",";
134         var fn = function(m, name, format, args){
135             if(format && useF){
136                 args = args ? ',' + args : "";
137                 if(format.substr(0, 5) != "this."){
138                     format = "fm." + format + '(';
139                 }else{
140                     format = 'this.call("'+ format.substr(5) + '", ';
141                     args = ", values";
142                 }
143             }else{
144                 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
145             }
146             return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
147         };
148         var body;
149         // branched to use + in gecko and [].join() in others
150         if(Roo.isGecko){
151             body = "this.compiled = function(values){ return '" +
152                    this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
153                     "';};";
154         }else{
155             body = ["this.compiled = function(values){ return ['"];
156             body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
157             body.push("'].join('');};");
158             body = body.join('');
159         }
160         /**
161          * eval:var:values
162          * eval:var:fm
163          */
164         eval(body);
165         return this;
166     },
167     
168     // private function used to call members
169     call : function(fnName, value, allValues){
170         return this[fnName](value, allValues);
171     },
172     
173     /**
174      * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
175      * @param {String/HTMLElement/Roo.Element} el The context element
176      * @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'})
177      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
178      * @return {HTMLElement/Roo.Element} The new node or Element
179      */
180     insertFirst: function(el, values, returnElement){
181         return this.doInsert('afterBegin', el, values, returnElement);
182     },
183
184     /**
185      * Applies the supplied values to the template and inserts the new node(s) before el.
186      * @param {String/HTMLElement/Roo.Element} el The context element
187      * @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'})
188      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
189      * @return {HTMLElement/Roo.Element} The new node or Element
190      */
191     insertBefore: function(el, values, returnElement){
192         return this.doInsert('beforeBegin', el, values, returnElement);
193     },
194
195     /**
196      * Applies the supplied values to the template and inserts the new node(s) after el.
197      * @param {String/HTMLElement/Roo.Element} el The context element
198      * @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'})
199      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
200      * @return {HTMLElement/Roo.Element} The new node or Element
201      */
202     insertAfter : function(el, values, returnElement){
203         return this.doInsert('afterEnd', el, values, returnElement);
204     },
205     
206     /**
207      * Applies the supplied values to the template and appends the new node(s) to el.
208      * @param {String/HTMLElement/Roo.Element} el The context element
209      * @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'})
210      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
211      * @return {HTMLElement/Roo.Element} The new node or Element
212      */
213     append : function(el, values, returnElement){
214         return this.doInsert('beforeEnd', el, values, returnElement);
215     },
216
217     doInsert : function(where, el, values, returnEl){
218         el = Roo.getDom(el);
219         var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
220         return returnEl ? Roo.get(newNode, true) : newNode;
221     },
222
223     /**
224      * Applies the supplied values to the template and overwrites the content of el with the new node(s).
225      * @param {String/HTMLElement/Roo.Element} el The context element
226      * @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'})
227      * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
228      * @return {HTMLElement/Roo.Element} The new node or Element
229      */
230     overwrite : function(el, values, returnElement){
231         el = Roo.getDom(el);
232         el.innerHTML = this.applyTemplate(values);
233         return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
234     }
235 };
236 /**
237  * Alias for {@link #applyTemplate}
238  * @method
239  */
240 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
241
242 // backwards compat
243 Roo.DomHelper.Template = Roo.Template;
244
245 /**
246  * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
247  * @param {String/HTMLElement} el A DOM element or its id
248  * @returns {Roo.Template} The created template
249  * @static
250  */
251 Roo.Template.from = function(el){
252     el = Roo.getDom(el);
253     return new Roo.Template(el.value || el.innerHTML);
254 };