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)
95 for(var i = tpls.length-1; i >= 0; --i){
96 this.compileTpl(tpls[i]);
97 this.tpls[tpls[i].id] = tpls[i];
99 this.master = tpls[0];
105 compileNode : function(node) {
109 // skip anything not a tag..
110 if (node.nodeType != 1) {
128 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
129 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
130 case (node.hasAttribute('roo-if')): tpl.attr = 'name'; break;
131 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
135 // just itterate children..
136 this.iterChild(node,this.compileNode)
140 var value = node.getAttribute('roo-' + tpl.attr);
141 node.removeAttribute('roo-'+ tpl.attr);
142 if (tpl.attr != 'name') {
143 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
144 node.parentNode.replaceChild(placeholder, node);
146 node.parentNode.removeChild(node);
149 // parent now sees '{domtplXXXX}
150 this.iterChild(node,this.compileNode)
152 // we should now have node body...
153 var div = document.createElement('div');
154 div.appendChild(node);
155 tpl.body = div.innerHTML;
162 switch (attr.value) {
163 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
164 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
165 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
170 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
174 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
178 tpl.id = value; // replace non characters???
190 oldwrapper : function ()
192 s = ['<tpl>', s, '</tpl>'].join('');
194 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
195 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
196 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
197 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
198 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
203 while(true == !!(m = s.match(re))){
204 var forMatch = m[0].match(nameRe),
205 ifMatch = m[0].match(ifRe),
206 execMatch = m[0].match(execRe),
207 namedMatch = m[0].match(namedRe),
212 name = forMatch && forMatch[1] ? forMatch[1] : '';
215 // if - puts fn into test..
216 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
218 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
223 // exec - calls a function... returns empty if true is returned.
224 exp = execMatch && execMatch[1] ? execMatch[1] : null;
226 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
234 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
235 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
236 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
239 var uid = namedMatch ? namedMatch[1] : id;
243 id: namedMatch ? namedMatch[1] : id,
250 s = s.replace(m[0], '');
252 s = s.replace(m[0], '{xtpl'+ id + '}');
259 * same as applyTemplate, except it's done to one of the subTemplates
260 * when using named templates, you can do:
262 * var str = pl.applySubTemplate('your-name', values);
265 * @param {Number} id of the template
266 * @param {Object} values to apply to template
267 * @param {Object} parent (normaly the instance of this object)
269 applySubTemplate : function(id, values, parent)
273 var t = this.tpls[id];
277 if(t.test && !t.test.call(this, values, parent)){
281 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
282 Roo.log(e.toString());
288 if(t.exec && t.exec.call(this, values, parent)){
292 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
293 Roo.log(e.toString());
298 var vs = t.target ? t.target.call(this, values, parent) : values;
299 parent = t.target ? values : parent;
300 if(t.target && vs instanceof Array){
302 for(var i = 0, len = vs.length; i < len; i++){
303 buf[buf.length] = t.compiled.call(this, vs[i], parent);
307 return t.compiled.call(this, vs, parent);
309 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
310 Roo.log(e.toString());
316 compileTpl : function(tpl)
318 var fm = Roo.util.Format;
319 var useF = this.disableFormats !== true;
320 var sep = Roo.isGecko ? "+" : ",";
321 var undef = function(str) {
322 Roo.log("Property not found :" + str);
326 var fn = function(m, name, format, args)
328 //Roo.log(arguments);
329 args = args ? args.replace(/\\'/g,"'") : args;
330 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
331 if (typeof(format) == 'undefined') {
332 format= 'htmlEncode';
334 if (format == 'raw' ) {
338 if(name.substr(0, 4) == 'xtpl'){
339 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
342 // build an array of options to determine if value is undefined..
344 // basically get 'xxxx.yyyy' then do
345 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
346 // (function () { Roo.log("Property not found"); return ''; })() :
351 Roo.each(name.split('.'), function(st) {
352 lookfor += (lookfor.length ? '.': '') + st;
353 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
356 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
361 args = args ? ',' + args : "";
363 if(format.substr(0, 5) != "this."){
364 format = "fm." + format + '(';
366 format = 'this.call("'+ format.substr(5) + '", ';
370 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
374 // called with xxyx.yuu:(test,test)
376 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
378 // raw.. - :raw modifier..
379 return "'"+ sep + udef_st + name + ")"+sep+"'";
383 // branched to use + in gecko and [].join() in others
385 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
386 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
389 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
390 body.push(tpl.body.replace(/(\r\n|\n)/g,
391 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
392 body.push("'].join('');};};");
393 body = body.join('');
396 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
398 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
404 applyTemplate : function(values){
405 return this.master.compiled.call(this, values, {});
410 return this.applyTemplate.apply(this, arguments);
415 Roo.XTemplate.from = function(el){
417 return new Roo.XTemplate(el.value || el.innerHTML);