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 = '<div>' + this.html + '</div>';
90 this.iterChild(div, function(n) {_t.compileNode(n, true); });
93 Roo.log(div.innerHTML);
97 Roo.each(tpls, function(tp){
99 this.tpls[tp.id] = tp;
102 this.master = tpls[0];
108 compileNode : function(node, istop) {
112 // skip anything not a tag..
113 if (node.nodeType != 1) {
132 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
133 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
134 case (node.hasAttribute('roo-if')): tpl.attr = 'name'; break;
135 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
139 // just itterate children..
140 this.iterChild(node,this.compileNode)
144 var value = node.getAttribute('roo-' + tpl.attr);
145 node.removeAttribute('roo-'+ tpl.attr);
146 if (tpl.attr != 'name') {
147 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
148 node.parentNode.replaceChild(placeholder, node);
150 node.parentNode.removeChild(node);
153 // parent now sees '{domtplXXXX}
154 this.iterChild(node,this.compileNode)
156 // we should now have node body...
157 var div = document.createElement('div');
158 div.appendChild(node);
160 tpl.body = div.innerHTML;
168 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
169 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
170 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
175 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
179 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
183 tpl.id = value; // replace non characters???
195 oldwrapper : function ()
197 s = ['<tpl>', s, '</tpl>'].join('');
199 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
200 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
201 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
202 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
203 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
208 while(true == !!(m = s.match(re))){
209 var forMatch = m[0].match(nameRe),
210 ifMatch = m[0].match(ifRe),
211 execMatch = m[0].match(execRe),
212 namedMatch = m[0].match(namedRe),
217 name = forMatch && forMatch[1] ? forMatch[1] : '';
220 // if - puts fn into test..
221 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
223 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
228 // exec - calls a function... returns empty if true is returned.
229 exp = execMatch && execMatch[1] ? execMatch[1] : null;
231 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
239 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
240 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
241 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
244 var uid = namedMatch ? namedMatch[1] : id;
248 id: namedMatch ? namedMatch[1] : id,
255 s = s.replace(m[0], '');
257 s = s.replace(m[0], '{xtpl'+ id + '}');
264 * same as applyTemplate, except it's done to one of the subTemplates
265 * when using named templates, you can do:
267 * var str = pl.applySubTemplate('your-name', values);
270 * @param {Number} id of the template
271 * @param {Object} values to apply to template
272 * @param {Object} parent (normaly the instance of this object)
274 applySubTemplate : function(id, values, parent)
278 var t = this.tpls[id];
282 if(t.ifCall && !t.ifCall.call(this, values, parent)){
286 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
287 Roo.log(e.toString());
293 if(t.execCall && t.execCall.call(this, values, parent)){
297 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
298 Roo.log(e.toString());
303 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
304 parent = t.target ? values : parent;
305 if(t.forCall && vs instanceof Array){
307 for(var i = 0, len = vs.length; i < len; i++){
308 buf[buf.length] = t.compiled.call(this, vs[i], parent);
312 return t.compiled.call(this, vs, parent);
314 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
315 Roo.log(e.toString());
321 compileTpl : function(tpl)
323 var fm = Roo.util.Format;
324 var useF = this.disableFormats !== true;
325 var sep = Roo.isGecko ? "+\n" : ",\n";
326 var undef = function(str) {
327 Roo.log("Property not found :" + str);
331 var fn = function(m, name, format, args)
333 //Roo.log(arguments);
334 args = args ? args.replace(/\\'/g,"'") : args;
335 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
336 if (typeof(format) == 'undefined') {
337 format= 'htmlEncode';
339 if (format == 'raw' ) {
343 if(name.substr(0, 6) == 'domtpl'){
344 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
347 // build an array of options to determine if value is undefined..
349 // basically get 'xxxx.yyyy' then do
350 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
351 // (function () { Roo.log("Property not found"); return ''; })() :
356 Roo.each(name.split('.'), function(st) {
357 lookfor += (lookfor.length ? '.': '') + st;
358 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
361 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
366 args = args ? ',' + args : "";
368 if(format.substr(0, 5) != "this."){
369 format = "fm." + format + '(';
371 format = 'this.call("'+ format.substr(5) + '", ';
375 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
379 // called with xxyx.yuu:(test,test)
381 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
383 // raw.. - :raw modifier..
384 return "'"+ sep + udef_st + name + ")"+sep+"'";
388 // branched to use + in gecko and [].join() in others
390 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
391 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
394 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
395 body.push(tpl.body.replace(/(\r\n|\n)/g,
396 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
397 body.push("'].join('');};};");
398 body = body.join('');
401 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
403 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
409 applyTemplate : function(values){
410 return this.master.compiled.call(this, values, {});
415 return this.applyTemplate.apply(this, arguments);
420 Roo.XTemplate.from = function(el){
422 return new Roo.XTemplate(el.value || el.innerHTML);