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); });
94 // create a top level template from the snippet..
96 Roo.log(div.innerHTML);
103 body : div.innerHTML,
115 Roo.each(tpls, function(tp){
117 this.tpls[tp.id] = tp;
120 this.master = tpls[0];
126 compileNode : function(node, istop) {
130 // skip anything not a tag..
131 if (node.nodeType != 1) {
150 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
151 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
152 case (node.hasAttribute('roo-if')): tpl.attr = 'name'; break;
153 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
157 // just itterate children..
158 this.iterChild(node,this.compileNode)
162 var value = node.getAttribute('roo-' + tpl.attr);
163 node.removeAttribute('roo-'+ tpl.attr);
164 if (tpl.attr != 'name') {
165 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
166 node.parentNode.replaceChild(placeholder, node);
168 node.parentNode.removeChild(node);
171 // parent now sees '{domtplXXXX}
172 this.iterChild(node,this.compileNode)
174 // we should now have node body...
175 var div = document.createElement('div');
176 div.appendChild(node);
178 tpl.body = div.innerHTML;
186 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
187 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
188 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
193 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
197 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
201 tpl.id = value; // replace non characters???
213 oldwrapper : function ()
215 s = ['<tpl>', s, '</tpl>'].join('');
217 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
218 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
219 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
220 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
221 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
226 while(true == !!(m = s.match(re))){
227 var forMatch = m[0].match(nameRe),
228 ifMatch = m[0].match(ifRe),
229 execMatch = m[0].match(execRe),
230 namedMatch = m[0].match(namedRe),
235 name = forMatch && forMatch[1] ? forMatch[1] : '';
238 // if - puts fn into test..
239 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
241 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
246 // exec - calls a function... returns empty if true is returned.
247 exp = execMatch && execMatch[1] ? execMatch[1] : null;
249 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
257 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
258 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
259 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
262 var uid = namedMatch ? namedMatch[1] : id;
266 id: namedMatch ? namedMatch[1] : id,
273 s = s.replace(m[0], '');
275 s = s.replace(m[0], '{xtpl'+ id + '}');
282 * same as applyTemplate, except it's done to one of the subTemplates
283 * when using named templates, you can do:
285 * var str = pl.applySubTemplate('your-name', values);
288 * @param {Number} id of the template
289 * @param {Object} values to apply to template
290 * @param {Object} parent (normaly the instance of this object)
292 applySubTemplate : function(id, values, parent)
296 var t = this.tpls[id];
300 if(t.ifCall && !t.ifCall.call(this, values, parent)){
304 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
305 Roo.log(e.toString());
311 if(t.execCall && t.execCall.call(this, values, parent)){
315 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
316 Roo.log(e.toString());
321 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
322 parent = t.target ? values : parent;
323 if(t.forCall && vs instanceof Array){
325 for(var i = 0, len = vs.length; i < len; i++){
326 buf[buf.length] = t.compiled.call(this, vs[i], parent);
330 return t.compiled.call(this, vs, parent);
332 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
333 Roo.log(e.toString());
339 compileTpl : function(tpl)
341 var fm = Roo.util.Format;
342 var useF = this.disableFormats !== true;
343 var sep = Roo.isGecko ? "+\n" : ",\n";
344 var undef = function(str) {
345 Roo.log("Property not found :" + str);
349 var fn = function(m, name, format, args)
351 //Roo.log(arguments);
352 args = args ? args.replace(/\\'/g,"'") : args;
353 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
354 if (typeof(format) == 'undefined') {
355 format= 'htmlEncode';
357 if (format == 'raw' ) {
361 if(name.substr(0, 6) == 'domtpl'){
362 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
365 // build an array of options to determine if value is undefined..
367 // basically get 'xxxx.yyyy' then do
368 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
369 // (function () { Roo.log("Property not found"); return ''; })() :
374 Roo.each(name.split('.'), function(st) {
375 lookfor += (lookfor.length ? '.': '') + st;
376 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
379 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
384 args = args ? ',' + args : "";
386 if(format.substr(0, 5) != "this."){
387 format = "fm." + format + '(';
389 format = 'this.call("'+ format.substr(5) + '", ';
393 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
397 // called with xxyx.yuu:(test,test)
399 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
401 // raw.. - :raw modifier..
402 return "'"+ sep + udef_st + name + ")"+sep+"'";
406 // branched to use + in gecko and [].join() in others
408 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
409 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
412 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
413 body.push(tpl.body.replace(/(\r\n|\n)/g,
414 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
415 body.push("'].join('');};};");
416 body = body.join('');
419 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
421 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
427 applyTemplate : function(values){
428 return this.master.compiled.call(this, values, {});
433 return this.applyTemplate.apply(this, arguments);
438 Roo.XTemplate.from = function(el){
440 return new Roo.XTemplate(el.value || el.innerHTML);