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, {
52 * The various sub templates
57 * basic tag replacing syntax
60 * // you can fake an object call by doing this
64 re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
67 iterChild : function (node, method) {
68 for( var i = 0; i < node.childNodes.length; i++) {
69 method.call(this, node.childNodes[i]);
74 * compile the template
76 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
83 // covert the html into DOM...
85 var div = document.createElement('div');
86 div.innerHTML = this.html;
88 this.iterChild(div, this.compileNode)
93 compileNode : function(node) {
97 // skip anything not a tag..
98 if (node.nodeType != 1) {
116 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
117 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
118 case (node.hasAttribute('roo-if')): tpl.attr = 'name'; break;
119 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
123 // just itterate children..
124 this.iterChild(node,this.compileNode)
128 var value = node.getAttribute('roo-' + tpl.attr);
129 node.removeAttribute('roo-'+ tpl.attr);
130 if (tpl.attr != 'name') {
131 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
132 node.parentNode.replaceChild(placeholder, node);
134 node.parentNode.removeChild(node);
137 // parent now sees '{domtplXXXX}
138 this.iterChild(node,this.compileNode)
140 // we should now have node body...
141 var div = document.createElement('div');
142 div.appendChild(node);
143 tpl.body = div.innerHTML;
146 Roo.log("TEMPLATE : " + tpl.uid);
152 switch (attr.value) {
153 case '.': attr.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
154 case '..': attr.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
155 default: attr.forCall= new Function('values', 'parent', 'with(values){ return '+attr.value+'; }');
160 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(attr.value))+'; }');
164 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(attr.value))+'; }');
168 tpl.id = value; // replace non characters???
176 id: attr == 'name' ? value : id,
187 oldwrapper : function ()
189 s = ['<tpl>', s, '</tpl>'].join('');
191 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
192 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
193 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
194 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
195 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
200 while(true == !!(m = s.match(re))){
201 var forMatch = m[0].match(nameRe),
202 ifMatch = m[0].match(ifRe),
203 execMatch = m[0].match(execRe),
204 namedMatch = m[0].match(namedRe),
209 name = forMatch && forMatch[1] ? forMatch[1] : '';
212 // if - puts fn into test..
213 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
215 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
220 // exec - calls a function... returns empty if true is returned.
221 exp = execMatch && execMatch[1] ? execMatch[1] : null;
223 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
231 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
232 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
233 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
236 var uid = namedMatch ? namedMatch[1] : id;
240 id: namedMatch ? namedMatch[1] : id,
247 s = s.replace(m[0], '');
249 s = s.replace(m[0], '{xtpl'+ id + '}');
254 for(var i = tpls.length-1; i >= 0; --i){
255 this.compileTpl(tpls[i]);
256 this.tpls[tpls[i].id] = tpls[i];
258 this.master = tpls[tpls.length-1];
262 * same as applyTemplate, except it's done to one of the subTemplates
263 * when using named templates, you can do:
265 * var str = pl.applySubTemplate('your-name', values);
268 * @param {Number} id of the template
269 * @param {Object} values to apply to template
270 * @param {Object} parent (normaly the instance of this object)
272 applySubTemplate : function(id, values, parent)
276 var t = this.tpls[id];
280 if(t.test && !t.test.call(this, values, parent)){
284 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
285 Roo.log(e.toString());
291 if(t.exec && t.exec.call(this, values, parent)){
295 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
296 Roo.log(e.toString());
301 var vs = t.target ? t.target.call(this, values, parent) : values;
302 parent = t.target ? values : parent;
303 if(t.target && vs instanceof Array){
305 for(var i = 0, len = vs.length; i < len; i++){
306 buf[buf.length] = t.compiled.call(this, vs[i], parent);
310 return t.compiled.call(this, vs, parent);
312 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
313 Roo.log(e.toString());
319 compileTpl : function(tpl)
321 var fm = Roo.util.Format;
322 var useF = this.disableFormats !== true;
323 var sep = Roo.isGecko ? "+" : ",";
324 var undef = function(str) {
325 Roo.log("Property not found :" + str);
329 var fn = function(m, name, format, args)
331 //Roo.log(arguments);
332 args = args ? args.replace(/\\'/g,"'") : args;
333 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
334 if (typeof(format) == 'undefined') {
335 format= 'htmlEncode';
337 if (format == 'raw' ) {
341 if(name.substr(0, 4) == 'xtpl'){
342 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
345 // build an array of options to determine if value is undefined..
347 // basically get 'xxxx.yyyy' then do
348 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
349 // (function () { Roo.log("Property not found"); return ''; })() :
354 Roo.each(name.split('.'), function(st) {
355 lookfor += (lookfor.length ? '.': '') + st;
356 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
359 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
364 args = args ? ',' + args : "";
366 if(format.substr(0, 5) != "this."){
367 format = "fm." + format + '(';
369 format = 'this.call("'+ format.substr(5) + '", ';
373 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
377 // called with xxyx.yuu:(test,test)
379 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
381 // raw.. - :raw modifier..
382 return "'"+ sep + udef_st + name + ")"+sep+"'";
386 // branched to use + in gecko and [].join() in others
388 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
389 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
392 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
393 body.push(tpl.body.replace(/(\r\n|\n)/g,
394 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
395 body.push("'].join('');};};");
396 body = body.join('');
399 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
401 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
407 applyTemplate : function(values){
408 return this.master.compiled.call(this, values, {});
413 return this.applyTemplate.apply(this, arguments);
418 Roo.XTemplate.from = function(el){
420 return new Roo.XTemplate(el.value || el.innerHTML);