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;
88 this.iterChild(div, this.compileNode)
93 compileNode : function(node) {
97 // skip anything not a tag..
98 if (node.nodeType != 1) {
104 case (node.hasAttribute('roo-for')): attr = 'for'; break;
105 case (node.hasAttribute('roo-if')): attr = 'if'; break;
106 case (node.hasAttribute('roo-if')): attr = 'name'; break;
107 case (node.hasAttribute('roo-exec')): attr = 'exec'; break;
111 // just itterate children..
112 this.iterChild(node,this.compileNode)
116 var value = node.getAttribute('roo-' + attr);
117 node.removeAttribute('roo-'+ attr);
118 if (attr != 'name') {
119 var placeholder = document.createTextNode('{domtpl' + id + '}');
120 node.parentNode.replaceChild(placeholder, node);
122 node.parentNode.removeChild(node);
125 // parent now sees '{domtplXXXX}
126 this.iterChild(node,this.compileNode)
128 // we should now have node body...
129 var div = document.createElement('div');
130 div.appendChild(node);
131 var html = div.innerHTML;
132 Roo.log("TEMPLATE : " + id);
136 id: attr == 'name' : value ? id,
147 oldwrapper : function ()
149 s = ['<tpl>', s, '</tpl>'].join('');
151 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
152 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
153 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
154 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
155 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
160 while(true == !!(m = s.match(re))){
161 var forMatch = m[0].match(nameRe),
162 ifMatch = m[0].match(ifRe),
163 execMatch = m[0].match(execRe),
164 namedMatch = m[0].match(namedRe),
169 name = forMatch && forMatch[1] ? forMatch[1] : '';
172 // if - puts fn into test..
173 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
175 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
180 // exec - calls a function... returns empty if true is returned.
181 exp = execMatch && execMatch[1] ? execMatch[1] : null;
183 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
191 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
192 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
193 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
196 var uid = namedMatch ? namedMatch[1] : id;
200 id: namedMatch ? namedMatch[1] : id,
207 s = s.replace(m[0], '');
209 s = s.replace(m[0], '{xtpl'+ id + '}');
214 for(var i = tpls.length-1; i >= 0; --i){
215 this.compileTpl(tpls[i]);
216 this.tpls[tpls[i].id] = tpls[i];
218 this.master = tpls[tpls.length-1];
222 * same as applyTemplate, except it's done to one of the subTemplates
223 * when using named templates, you can do:
225 * var str = pl.applySubTemplate('your-name', values);
228 * @param {Number} id of the template
229 * @param {Object} values to apply to template
230 * @param {Object} parent (normaly the instance of this object)
232 applySubTemplate : function(id, values, parent)
236 var t = this.tpls[id];
240 if(t.test && !t.test.call(this, values, parent)){
244 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
245 Roo.log(e.toString());
251 if(t.exec && t.exec.call(this, values, parent)){
255 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
256 Roo.log(e.toString());
261 var vs = t.target ? t.target.call(this, values, parent) : values;
262 parent = t.target ? values : parent;
263 if(t.target && vs instanceof Array){
265 for(var i = 0, len = vs.length; i < len; i++){
266 buf[buf.length] = t.compiled.call(this, vs[i], parent);
270 return t.compiled.call(this, vs, parent);
272 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
273 Roo.log(e.toString());
279 compileTpl : function(tpl)
281 var fm = Roo.util.Format;
282 var useF = this.disableFormats !== true;
283 var sep = Roo.isGecko ? "+" : ",";
284 var undef = function(str) {
285 Roo.log("Property not found :" + str);
289 var fn = function(m, name, format, args)
291 //Roo.log(arguments);
292 args = args ? args.replace(/\\'/g,"'") : args;
293 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
294 if (typeof(format) == 'undefined') {
295 format= 'htmlEncode';
297 if (format == 'raw' ) {
301 if(name.substr(0, 4) == 'xtpl'){
302 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
305 // build an array of options to determine if value is undefined..
307 // basically get 'xxxx.yyyy' then do
308 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
309 // (function () { Roo.log("Property not found"); return ''; })() :
314 Roo.each(name.split('.'), function(st) {
315 lookfor += (lookfor.length ? '.': '') + st;
316 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
319 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
324 args = args ? ',' + args : "";
326 if(format.substr(0, 5) != "this."){
327 format = "fm." + format + '(';
329 format = 'this.call("'+ format.substr(5) + '", ';
333 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
337 // called with xxyx.yuu:(test,test)
339 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
341 // raw.. - :raw modifier..
342 return "'"+ sep + udef_st + name + ")"+sep+"'";
346 // branched to use + in gecko and [].join() in others
348 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
349 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
352 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
353 body.push(tpl.body.replace(/(\r\n|\n)/g,
354 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
355 body.push("'].join('');};};");
356 body = body.join('');
359 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
361 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
367 applyTemplate : function(values){
368 return this.master.compiled.call(this, values, {});
373 return this.applyTemplate.apply(this, arguments);
378 Roo.XTemplate.from = function(el){
380 return new Roo.XTemplate(el.value || el.innerHTML);