10 * @class Roo.DomTemplate
11 * @extends Roo.Template
12 * An effort at a dom based template engine..
14 * Similar to XTemplate, except it uses dom parsing to create the template..
21 {a_variable} - output encoded.
22 {a_variable.format:("Y-m-d")} - call a method on the variable
23 {a_variable:raw} - unencoded output
24 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
25 {a_variable:this.method_on_template(...)} - call a method on the template object.
30 <div roo-for="a_variable or condition.."></tpl>
31 <tpl roo-if="a_variable or condition"></tpl>
32 <tpl roo-exec="some javascript"></tpl>
33 <tpl roo-name="named_template"></tpl>
38 Roo.DomTemplate = function()
40 Roo.DomTemplate.superclass.constructor.apply(this, arguments);
47 Roo.extend(Roo.DomTemplate, Roo.Template, {
50 * The various sub templates
55 * basic tag replacing syntax
58 * // you can fake an object call by doing this
62 re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
65 iterChild : function (node, method) {
66 for( var i = 0; i < node.childNodes.length; i++) {
67 method.call(this, node.childNodes[i]);
72 * compile the template
74 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
81 // covert the html into DOM...
83 var div = document.createElement('div');
84 div.innerHTML = this.html;
86 this.iterChild(div, this.compileNode)
91 compileNode : function(node) {
97 case (node.hasAttribute('roo-for')): attr = 'for'; break;
98 case (node.hasAttribute('roo-if')): attr = 'if'; break;
99 case (node.hasAttribute('roo-if')): attr = 'name'; break;
100 case (node.hasAttribute('roo-exec')): attr = 'exec'; break;
104 // just itterate children..
105 this.iterChild(node);
109 var value = node.getAttribute('roo-' + attr);
110 node.removeAttribute('roo-'+ attr);
111 if (attr != 'name') {
112 var placeholder = document.createTextNode('{domtpl' + id + '}');
113 node.parentNode.replaceChild(placeholder, node);
115 node.parentNode.removeChild(node);
118 // parent now sees '{domtplXXXX}
119 this.iterChild(node);
121 // we should now have node body...
122 var div = document.createElement('div');
123 div.appendChild(node);
124 var html = div.innerHTML;
125 Roo.log("TEMPLATE : " + id);
134 oldwrapper : function ()
136 s = ['<tpl>', s, '</tpl>'].join('');
138 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
139 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
140 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
141 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
142 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
147 while(true == !!(m = s.match(re))){
148 var forMatch = m[0].match(nameRe),
149 ifMatch = m[0].match(ifRe),
150 execMatch = m[0].match(execRe),
151 namedMatch = m[0].match(namedRe),
156 name = forMatch && forMatch[1] ? forMatch[1] : '';
159 // if - puts fn into test..
160 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
162 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
167 // exec - calls a function... returns empty if true is returned.
168 exp = execMatch && execMatch[1] ? execMatch[1] : null;
170 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
178 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
179 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
180 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
183 var uid = namedMatch ? namedMatch[1] : id;
187 id: namedMatch ? namedMatch[1] : id,
194 s = s.replace(m[0], '');
196 s = s.replace(m[0], '{xtpl'+ id + '}');
201 for(var i = tpls.length-1; i >= 0; --i){
202 this.compileTpl(tpls[i]);
203 this.tpls[tpls[i].id] = tpls[i];
205 this.master = tpls[tpls.length-1];
209 * same as applyTemplate, except it's done to one of the subTemplates
210 * when using named templates, you can do:
212 * var str = pl.applySubTemplate('your-name', values);
215 * @param {Number} id of the template
216 * @param {Object} values to apply to template
217 * @param {Object} parent (normaly the instance of this object)
219 applySubTemplate : function(id, values, parent)
223 var t = this.tpls[id];
227 if(t.test && !t.test.call(this, values, parent)){
231 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
232 Roo.log(e.toString());
238 if(t.exec && t.exec.call(this, values, parent)){
242 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
243 Roo.log(e.toString());
248 var vs = t.target ? t.target.call(this, values, parent) : values;
249 parent = t.target ? values : parent;
250 if(t.target && vs instanceof Array){
252 for(var i = 0, len = vs.length; i < len; i++){
253 buf[buf.length] = t.compiled.call(this, vs[i], parent);
257 return t.compiled.call(this, vs, parent);
259 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
260 Roo.log(e.toString());
266 compileTpl : function(tpl)
268 var fm = Roo.util.Format;
269 var useF = this.disableFormats !== true;
270 var sep = Roo.isGecko ? "+" : ",";
271 var undef = function(str) {
272 Roo.log("Property not found :" + str);
276 var fn = function(m, name, format, args)
278 //Roo.log(arguments);
279 args = args ? args.replace(/\\'/g,"'") : args;
280 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
281 if (typeof(format) == 'undefined') {
282 format= 'htmlEncode';
284 if (format == 'raw' ) {
288 if(name.substr(0, 4) == 'xtpl'){
289 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
292 // build an array of options to determine if value is undefined..
294 // basically get 'xxxx.yyyy' then do
295 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
296 // (function () { Roo.log("Property not found"); return ''; })() :
301 Roo.each(name.split('.'), function(st) {
302 lookfor += (lookfor.length ? '.': '') + st;
303 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
306 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
311 args = args ? ',' + args : "";
313 if(format.substr(0, 5) != "this."){
314 format = "fm." + format + '(';
316 format = 'this.call("'+ format.substr(5) + '", ';
320 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
324 // called with xxyx.yuu:(test,test)
326 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
328 // raw.. - :raw modifier..
329 return "'"+ sep + udef_st + name + ")"+sep+"'";
333 // branched to use + in gecko and [].join() in others
335 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
336 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
339 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
340 body.push(tpl.body.replace(/(\r\n|\n)/g,
341 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
342 body.push("'].join('');};};");
343 body = body.join('');
346 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
348 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
354 applyTemplate : function(values){
355 return this.master.compiled.call(this, values, {});
360 return this.applyTemplate.apply(this, arguments);
365 Roo.XTemplate.from = function(el){
367 return new Roo.XTemplate(el.value || el.innerHTML);