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