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);
100 Roo.each(tpls, function(tp){
102 this.tpls[tp.id] = tp;
105 this.master = tpls[0];
111 compileNode : function(node, istop) {
115 // skip anything not a tag..
116 if (node.nodeType != 1) {
135 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
136 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
137 case (node.hasAttribute('roo-if')): tpl.attr = 'name'; break;
138 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
142 // just itterate children..
143 this.iterChild(node,this.compileNode)
147 var value = node.getAttribute('roo-' + tpl.attr);
148 node.removeAttribute('roo-'+ tpl.attr);
149 if (tpl.attr != 'name') {
150 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
151 node.parentNode.replaceChild(placeholder, node);
153 node.parentNode.removeChild(node);
156 // parent now sees '{domtplXXXX}
157 this.iterChild(node,this.compileNode)
159 // we should now have node body...
160 var div = document.createElement('div');
161 div.appendChild(node);
163 tpl.body = div.innerHTML;
171 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
172 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
173 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
178 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
182 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
186 tpl.id = value; // replace non characters???
198 oldwrapper : function ()
200 s = ['<tpl>', s, '</tpl>'].join('');
202 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
203 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
204 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
205 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
206 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
211 while(true == !!(m = s.match(re))){
212 var forMatch = m[0].match(nameRe),
213 ifMatch = m[0].match(ifRe),
214 execMatch = m[0].match(execRe),
215 namedMatch = m[0].match(namedRe),
220 name = forMatch && forMatch[1] ? forMatch[1] : '';
223 // if - puts fn into test..
224 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
226 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
231 // exec - calls a function... returns empty if true is returned.
232 exp = execMatch && execMatch[1] ? execMatch[1] : null;
234 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
242 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
243 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
244 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
247 var uid = namedMatch ? namedMatch[1] : id;
251 id: namedMatch ? namedMatch[1] : id,
258 s = s.replace(m[0], '');
260 s = s.replace(m[0], '{xtpl'+ id + '}');
267 * same as applyTemplate, except it's done to one of the subTemplates
268 * when using named templates, you can do:
270 * var str = pl.applySubTemplate('your-name', values);
273 * @param {Number} id of the template
274 * @param {Object} values to apply to template
275 * @param {Object} parent (normaly the instance of this object)
277 applySubTemplate : function(id, values, parent)
281 var t = this.tpls[id];
285 if(t.ifCall && !t.ifCall.call(this, values, parent)){
289 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
290 Roo.log(e.toString());
296 if(t.execCall && t.execCall.call(this, values, parent)){
300 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
301 Roo.log(e.toString());
306 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
307 parent = t.target ? values : parent;
308 if(t.forCall && vs instanceof Array){
310 for(var i = 0, len = vs.length; i < len; i++){
311 buf[buf.length] = t.compiled.call(this, vs[i], parent);
315 return t.compiled.call(this, vs, parent);
317 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
318 Roo.log(e.toString());
324 compileTpl : function(tpl)
326 var fm = Roo.util.Format;
327 var useF = this.disableFormats !== true;
328 var sep = Roo.isGecko ? "+\n" : ",\n";
329 var undef = function(str) {
330 Roo.log("Property not found :" + str);
334 var fn = function(m, name, format, args)
336 //Roo.log(arguments);
337 args = args ? args.replace(/\\'/g,"'") : args;
338 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
339 if (typeof(format) == 'undefined') {
340 format= 'htmlEncode';
342 if (format == 'raw' ) {
346 if(name.substr(0, 6) == 'domtpl'){
347 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
350 // build an array of options to determine if value is undefined..
352 // basically get 'xxxx.yyyy' then do
353 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
354 // (function () { Roo.log("Property not found"); return ''; })() :
359 Roo.each(name.split('.'), function(st) {
360 lookfor += (lookfor.length ? '.': '') + st;
361 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
364 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
369 args = args ? ',' + args : "";
371 if(format.substr(0, 5) != "this."){
372 format = "fm." + format + '(';
374 format = 'this.call("'+ format.substr(5) + '", ';
378 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
382 // called with xxyx.yuu:(test,test)
384 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
386 // raw.. - :raw modifier..
387 return "'"+ sep + udef_st + name + ")"+sep+"'";
391 // branched to use + in gecko and [].join() in others
393 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
394 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
397 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
398 body.push(tpl.body.replace(/(\r\n|\n)/g,
399 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
400 body.push("'].join('');};};");
401 body = body.join('');
404 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
406 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
412 applyTemplate : function(values){
413 return this.master.compiled.call(this, values, {});
418 return this.applyTemplate.apply(this, arguments);
423 Roo.XTemplate.from = function(el){
425 return new Roo.XTemplate(el.value || el.innerHTML);