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, this.compileNode)
96 Roo.each(tpls, function(tp){
98 this.tpls[tp.id] = tp;
101 this.master = tpls[0];
107 compileNode : function(node) {
111 // skip anything not a tag..
112 if (node.nodeType != 1) {
130 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
131 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
132 case (node.hasAttribute('roo-if')): tpl.attr = 'name'; break;
133 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
137 // just itterate children..
138 this.iterChild(node,this.compileNode)
142 var value = node.getAttribute('roo-' + tpl.attr);
143 node.removeAttribute('roo-'+ tpl.attr);
144 if (tpl.attr != 'name') {
145 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
146 node.parentNode.replaceChild(placeholder, node);
148 node.parentNode.removeChild(node);
151 // parent now sees '{domtplXXXX}
152 this.iterChild(node,this.compileNode)
154 // we should now have node body...
155 var div = document.createElement('div');
156 div.appendChild(node);
157 tpl.body = div.innerHTML;
164 switch (attr.value) {
165 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
166 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
167 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
172 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
176 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
180 tpl.id = value; // replace non characters???
192 oldwrapper : function ()
194 s = ['<tpl>', s, '</tpl>'].join('');
196 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
197 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
198 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
199 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
200 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
205 while(true == !!(m = s.match(re))){
206 var forMatch = m[0].match(nameRe),
207 ifMatch = m[0].match(ifRe),
208 execMatch = m[0].match(execRe),
209 namedMatch = m[0].match(namedRe),
214 name = forMatch && forMatch[1] ? forMatch[1] : '';
217 // if - puts fn into test..
218 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
220 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
225 // exec - calls a function... returns empty if true is returned.
226 exp = execMatch && execMatch[1] ? execMatch[1] : null;
228 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
236 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
237 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
238 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
241 var uid = namedMatch ? namedMatch[1] : id;
245 id: namedMatch ? namedMatch[1] : id,
252 s = s.replace(m[0], '');
254 s = s.replace(m[0], '{xtpl'+ id + '}');
261 * same as applyTemplate, except it's done to one of the subTemplates
262 * when using named templates, you can do:
264 * var str = pl.applySubTemplate('your-name', values);
267 * @param {Number} id of the template
268 * @param {Object} values to apply to template
269 * @param {Object} parent (normaly the instance of this object)
271 applySubTemplate : function(id, values, parent)
275 var t = this.tpls[id];
279 if(t.test && !t.test.call(this, values, parent)){
283 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
284 Roo.log(e.toString());
290 if(t.exec && t.exec.call(this, values, parent)){
294 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
295 Roo.log(e.toString());
300 var vs = t.target ? t.target.call(this, values, parent) : values;
301 parent = t.target ? values : parent;
302 if(t.target && vs instanceof Array){
304 for(var i = 0, len = vs.length; i < len; i++){
305 buf[buf.length] = t.compiled.call(this, vs[i], parent);
309 return t.compiled.call(this, vs, parent);
311 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
312 Roo.log(e.toString());
318 compileTpl : function(tpl)
320 var fm = Roo.util.Format;
321 var useF = this.disableFormats !== true;
322 var sep = Roo.isGecko ? "+" : ",";
323 var undef = function(str) {
324 Roo.log("Property not found :" + str);
328 var fn = function(m, name, format, args)
330 //Roo.log(arguments);
331 args = args ? args.replace(/\\'/g,"'") : args;
332 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
333 if (typeof(format) == 'undefined') {
334 format= 'htmlEncode';
336 if (format == 'raw' ) {
340 if(name.substr(0, 4) == 'xtpl'){
341 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
344 // build an array of options to determine if value is undefined..
346 // basically get 'xxxx.yyyy' then do
347 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
348 // (function () { Roo.log("Property not found"); return ''; })() :
353 Roo.each(name.split('.'), function(st) {
354 lookfor += (lookfor.length ? '.': '') + st;
355 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
358 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
363 args = args ? ',' + args : "";
365 if(format.substr(0, 5) != "this."){
366 format = "fm." + format + '(';
368 format = 'this.call("'+ format.substr(5) + '", ';
372 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
376 // called with xxyx.yuu:(test,test)
378 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
380 // raw.. - :raw modifier..
381 return "'"+ sep + udef_st + name + ")"+sep+"'";
385 // branched to use + in gecko and [].join() in others
387 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
388 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
391 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
392 body.push(tpl.body.replace(/(\r\n|\n)/g,
393 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
394 body.push("'].join('');};};");
395 body = body.join('');
398 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
400 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
406 applyTemplate : function(values){
407 return this.master.compiled.call(this, values, {});
412 return this.applyTemplate.apply(this, arguments);
417 Roo.XTemplate.from = function(el){
419 return new Roo.XTemplate(el.value || el.innerHTML);