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);
141 oldwrapper : function ()
143 s = ['<tpl>', s, '</tpl>'].join('');
145 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
146 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
147 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
148 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
149 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
154 while(true == !!(m = s.match(re))){
155 var forMatch = m[0].match(nameRe),
156 ifMatch = m[0].match(ifRe),
157 execMatch = m[0].match(execRe),
158 namedMatch = m[0].match(namedRe),
163 name = forMatch && forMatch[1] ? forMatch[1] : '';
166 // if - puts fn into test..
167 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
169 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
174 // exec - calls a function... returns empty if true is returned.
175 exp = execMatch && execMatch[1] ? execMatch[1] : null;
177 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
185 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
186 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
187 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
190 var uid = namedMatch ? namedMatch[1] : id;
194 id: namedMatch ? namedMatch[1] : id,
201 s = s.replace(m[0], '');
203 s = s.replace(m[0], '{xtpl'+ id + '}');
208 for(var i = tpls.length-1; i >= 0; --i){
209 this.compileTpl(tpls[i]);
210 this.tpls[tpls[i].id] = tpls[i];
212 this.master = tpls[tpls.length-1];
216 * same as applyTemplate, except it's done to one of the subTemplates
217 * when using named templates, you can do:
219 * var str = pl.applySubTemplate('your-name', values);
222 * @param {Number} id of the template
223 * @param {Object} values to apply to template
224 * @param {Object} parent (normaly the instance of this object)
226 applySubTemplate : function(id, values, parent)
230 var t = this.tpls[id];
234 if(t.test && !t.test.call(this, values, parent)){
238 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
239 Roo.log(e.toString());
245 if(t.exec && t.exec.call(this, values, parent)){
249 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
250 Roo.log(e.toString());
255 var vs = t.target ? t.target.call(this, values, parent) : values;
256 parent = t.target ? values : parent;
257 if(t.target && vs instanceof Array){
259 for(var i = 0, len = vs.length; i < len; i++){
260 buf[buf.length] = t.compiled.call(this, vs[i], parent);
264 return t.compiled.call(this, vs, parent);
266 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
267 Roo.log(e.toString());
273 compileTpl : function(tpl)
275 var fm = Roo.util.Format;
276 var useF = this.disableFormats !== true;
277 var sep = Roo.isGecko ? "+" : ",";
278 var undef = function(str) {
279 Roo.log("Property not found :" + str);
283 var fn = function(m, name, format, args)
285 //Roo.log(arguments);
286 args = args ? args.replace(/\\'/g,"'") : args;
287 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
288 if (typeof(format) == 'undefined') {
289 format= 'htmlEncode';
291 if (format == 'raw' ) {
295 if(name.substr(0, 4) == 'xtpl'){
296 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
299 // build an array of options to determine if value is undefined..
301 // basically get 'xxxx.yyyy' then do
302 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
303 // (function () { Roo.log("Property not found"); return ''; })() :
308 Roo.each(name.split('.'), function(st) {
309 lookfor += (lookfor.length ? '.': '') + st;
310 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
313 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
318 args = args ? ',' + args : "";
320 if(format.substr(0, 5) != "this."){
321 format = "fm." + format + '(';
323 format = 'this.call("'+ format.substr(5) + '", ';
327 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
331 // called with xxyx.yuu:(test,test)
333 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
335 // raw.. - :raw modifier..
336 return "'"+ sep + udef_st + name + ")"+sep+"'";
340 // branched to use + in gecko and [].join() in others
342 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
343 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
346 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
347 body.push(tpl.body.replace(/(\r\n|\n)/g,
348 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
349 body.push("'].join('');};};");
350 body = body.join('');
353 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
355 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
361 applyTemplate : function(values){
362 return this.master.compiled.call(this, values, {});
367 return this.applyTemplate.apply(this, arguments);
372 Roo.XTemplate.from = function(el){
374 return new Roo.XTemplate(el.value || el.innerHTML);