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;
90 this.iterChild(div, function(n), this.compileNode, true);
96 Roo.each(tpls, function(tp){
98 this.tpls[tp.id] = tp;
101 this.master = tpls[0];
107 compileNode : function(node, istop) {
111 // skip anything not a tag..
112 if (node.nodeType != 1) {
131 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
132 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
133 case (node.hasAttribute('roo-if')): tpl.attr = 'name'; break;
134 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
138 // just itterate children..
139 this.iterChild(node,this.compileNode)
143 var value = node.getAttribute('roo-' + tpl.attr);
144 node.removeAttribute('roo-'+ tpl.attr);
145 if (tpl.attr != 'name') {
146 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
147 node.parentNode.replaceChild(placeholder, node);
149 node.parentNode.removeChild(node);
152 // parent now sees '{domtplXXXX}
153 this.iterChild(node,this.compileNode)
155 // we should now have node body...
156 var div = document.createElement('div');
157 div.appendChild(node);
159 tpl.body = div.innerHTML;
167 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
168 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
169 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
174 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
178 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
182 tpl.id = value; // replace non characters???
194 oldwrapper : function ()
196 s = ['<tpl>', s, '</tpl>'].join('');
198 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
199 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
200 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
201 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
202 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
207 while(true == !!(m = s.match(re))){
208 var forMatch = m[0].match(nameRe),
209 ifMatch = m[0].match(ifRe),
210 execMatch = m[0].match(execRe),
211 namedMatch = m[0].match(namedRe),
216 name = forMatch && forMatch[1] ? forMatch[1] : '';
219 // if - puts fn into test..
220 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
222 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
227 // exec - calls a function... returns empty if true is returned.
228 exp = execMatch && execMatch[1] ? execMatch[1] : null;
230 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
238 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
239 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
240 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
243 var uid = namedMatch ? namedMatch[1] : id;
247 id: namedMatch ? namedMatch[1] : id,
254 s = s.replace(m[0], '');
256 s = s.replace(m[0], '{xtpl'+ id + '}');
263 * same as applyTemplate, except it's done to one of the subTemplates
264 * when using named templates, you can do:
266 * var str = pl.applySubTemplate('your-name', values);
269 * @param {Number} id of the template
270 * @param {Object} values to apply to template
271 * @param {Object} parent (normaly the instance of this object)
273 applySubTemplate : function(id, values, parent)
277 var t = this.tpls[id];
281 if(t.ifCall && !t.ifCall.call(this, values, parent)){
285 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
286 Roo.log(e.toString());
292 if(t.execCall && t.execCall.call(this, values, parent)){
296 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
297 Roo.log(e.toString());
302 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
303 parent = t.target ? values : parent;
304 if(t.forCall && vs instanceof Array){
306 for(var i = 0, len = vs.length; i < len; i++){
307 buf[buf.length] = t.compiled.call(this, vs[i], parent);
311 return t.compiled.call(this, vs, parent);
313 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
314 Roo.log(e.toString());
320 compileTpl : function(tpl)
322 var fm = Roo.util.Format;
323 var useF = this.disableFormats !== true;
324 var sep = Roo.isGecko ? "+\n" : ",\n";
325 var undef = function(str) {
326 Roo.log("Property not found :" + str);
330 var fn = function(m, name, format, args)
332 //Roo.log(arguments);
333 args = args ? args.replace(/\\'/g,"'") : args;
334 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
335 if (typeof(format) == 'undefined') {
336 format= 'htmlEncode';
338 if (format == 'raw' ) {
342 if(name.substr(0, 6) == 'domtpl'){
343 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
346 // build an array of options to determine if value is undefined..
348 // basically get 'xxxx.yyyy' then do
349 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
350 // (function () { Roo.log("Property not found"); return ''; })() :
355 Roo.each(name.split('.'), function(st) {
356 lookfor += (lookfor.length ? '.': '') + st;
357 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
360 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
365 args = args ? ',' + args : "";
367 if(format.substr(0, 5) != "this."){
368 format = "fm." + format + '(';
370 format = 'this.call("'+ format.substr(5) + '", ';
374 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
378 // called with xxyx.yuu:(test,test)
380 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
382 // raw.. - :raw modifier..
383 return "'"+ sep + udef_st + name + ")"+sep+"'";
387 // branched to use + in gecko and [].join() in others
389 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
390 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
393 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
394 body.push(tpl.body.replace(/(\r\n|\n)/g,
395 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
396 body.push("'].join('');};};");
397 body = body.join('');
400 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
402 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
408 applyTemplate : function(values){
409 return this.master.compiled.call(this, values, {});
414 return this.applyTemplate.apply(this, arguments);
419 Roo.XTemplate.from = function(el){
421 return new Roo.XTemplate(el.value || el.innerHTML);