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) {
109 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
110 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
111 case (node.hasAttribute('roo-if')): tpl.attr = 'name'; break;
112 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
116 // just itterate children..
117 this.iterChild(node,this.compileNode)
121 var value = node.getAttribute('roo-' + tpl.attr);
122 node.removeAttribute('roo-'+ tpl.attr);
123 if (tpl.attr != 'name') {
124 var placeholder = document.createTextNode('{domtpl' + id + '}');
125 node.parentNode.replaceChild(placeholder, node);
127 node.parentNode.removeChild(node);
130 // parent now sees '{domtplXXXX}
131 this.iterChild(node,this.compileNode)
133 // we should now have node body...
134 var div = document.createElement('div');
135 div.appendChild(node);
136 var html = div.innerHTML;
137 Roo.log("TEMPLATE : " + id);
148 id: attr == 'name' ? value : id,
159 oldwrapper : function ()
161 s = ['<tpl>', s, '</tpl>'].join('');
163 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
164 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
165 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
166 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
167 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
172 while(true == !!(m = s.match(re))){
173 var forMatch = m[0].match(nameRe),
174 ifMatch = m[0].match(ifRe),
175 execMatch = m[0].match(execRe),
176 namedMatch = m[0].match(namedRe),
181 name = forMatch && forMatch[1] ? forMatch[1] : '';
184 // if - puts fn into test..
185 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
187 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
192 // exec - calls a function... returns empty if true is returned.
193 exp = execMatch && execMatch[1] ? execMatch[1] : null;
195 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
203 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
204 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
205 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
208 var uid = namedMatch ? namedMatch[1] : id;
212 id: namedMatch ? namedMatch[1] : id,
219 s = s.replace(m[0], '');
221 s = s.replace(m[0], '{xtpl'+ id + '}');
226 for(var i = tpls.length-1; i >= 0; --i){
227 this.compileTpl(tpls[i]);
228 this.tpls[tpls[i].id] = tpls[i];
230 this.master = tpls[tpls.length-1];
234 * same as applyTemplate, except it's done to one of the subTemplates
235 * when using named templates, you can do:
237 * var str = pl.applySubTemplate('your-name', values);
240 * @param {Number} id of the template
241 * @param {Object} values to apply to template
242 * @param {Object} parent (normaly the instance of this object)
244 applySubTemplate : function(id, values, parent)
248 var t = this.tpls[id];
252 if(t.test && !t.test.call(this, values, parent)){
256 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
257 Roo.log(e.toString());
263 if(t.exec && t.exec.call(this, values, parent)){
267 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
268 Roo.log(e.toString());
273 var vs = t.target ? t.target.call(this, values, parent) : values;
274 parent = t.target ? values : parent;
275 if(t.target && vs instanceof Array){
277 for(var i = 0, len = vs.length; i < len; i++){
278 buf[buf.length] = t.compiled.call(this, vs[i], parent);
282 return t.compiled.call(this, vs, parent);
284 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
285 Roo.log(e.toString());
291 compileTpl : function(tpl)
293 var fm = Roo.util.Format;
294 var useF = this.disableFormats !== true;
295 var sep = Roo.isGecko ? "+" : ",";
296 var undef = function(str) {
297 Roo.log("Property not found :" + str);
301 var fn = function(m, name, format, args)
303 //Roo.log(arguments);
304 args = args ? args.replace(/\\'/g,"'") : args;
305 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
306 if (typeof(format) == 'undefined') {
307 format= 'htmlEncode';
309 if (format == 'raw' ) {
313 if(name.substr(0, 4) == 'xtpl'){
314 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
317 // build an array of options to determine if value is undefined..
319 // basically get 'xxxx.yyyy' then do
320 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
321 // (function () { Roo.log("Property not found"); return ''; })() :
326 Roo.each(name.split('.'), function(st) {
327 lookfor += (lookfor.length ? '.': '') + st;
328 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
331 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
336 args = args ? ',' + args : "";
338 if(format.substr(0, 5) != "this."){
339 format = "fm." + format + '(';
341 format = 'this.call("'+ format.substr(5) + '", ';
345 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
349 // called with xxyx.yuu:(test,test)
351 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
353 // raw.. - :raw modifier..
354 return "'"+ sep + udef_st + name + ")"+sep+"'";
358 // branched to use + in gecko and [].join() in others
360 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
361 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
364 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
365 body.push(tpl.body.replace(/(\r\n|\n)/g,
366 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
367 body.push("'].join('');};};");
368 body = body.join('');
371 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
373 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
379 applyTemplate : function(values){
380 return this.master.compiled.call(this, values, {});
385 return this.applyTemplate.apply(this, arguments);
390 Roo.XTemplate.from = function(el){
392 return new Roo.XTemplate(el.value || el.innerHTML);