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.XTemplate = function()
40 Roo.XTemplate.superclass.constructor.apply(this, arguments);
47 Roo.extend(Roo.XTemplate, Roo.Template, {
50 * The various sub templates
55 * basic tag replacing syntax
58 * // you can fake an object call by doing this
62 re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
65 iterChild : function (node, method) {
66 for( var i = 0; i < node.childNodes.length; i++) {
67 method.call(this, node.childNodes[i]);
72 * compile the template
74 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
81 // covert the html into DOM...
83 var div = document.createElement('div');
84 div.innerHTML = this.html;
86 this.iterChild(div, this.compileNode)
91 compileNode : function(node) {
97 case (node.hasAttribute('roo-for')): attr = 'for'; break;
98 case (node.hasAttribute('roo-if')): attr = 'if'; break;
99 case (node.hasAttribute('roo-if')): attr = 'name'; break;
100 case (node.hasAttribute('roo-exec')): attr = 'exec'; break;
104 // just itterate children..
105 this.iterChild(node);
109 var value = node.getAttribute('roo-' + attr);
110 node.removeAttribute('roo-'+ attr);
111 if (attr != 'name') {
112 var placeholder = document.createTextNode('{domtpl' + id + '}');
113 node.parentNode.replaceChild(placeholder, node);
115 node.parentNode.removeChild(node);
118 // parent now sees '{domtplXXXX}
119 this.iterChild(node);
121 // we should now have node body...
122 var div = document.createElement('div');
123 div.appendChild(node);
124 var html = div.innerHTML;
125 Roo.log("TEMPLATE : " + id);
135 s = ['<tpl>', s, '</tpl>'].join('');
137 var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
138 nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
139 ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
140 execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
141 namedRe = /^<tpl\b[^>]*?name="(\w+)"/, // named templates..
146 while(true == !!(m = s.match(re))){
147 var forMatch = m[0].match(nameRe),
148 ifMatch = m[0].match(ifRe),
149 execMatch = m[0].match(execRe),
150 namedMatch = m[0].match(namedRe),
155 name = forMatch && forMatch[1] ? forMatch[1] : '';
158 // if - puts fn into test..
159 exp = ifMatch && ifMatch[1] ? ifMatch[1] : null;
161 fn = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(exp))+'; }');
166 // exec - calls a function... returns empty if true is returned.
167 exp = execMatch && execMatch[1] ? execMatch[1] : null;
169 exec = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(exp))+'; }');
177 case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
178 case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
179 default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
182 var uid = namedMatch ? namedMatch[1] : id;
186 id: namedMatch ? namedMatch[1] : id,
193 s = s.replace(m[0], '');
195 s = s.replace(m[0], '{xtpl'+ id + '}');
200 for(var i = tpls.length-1; i >= 0; --i){
201 this.compileTpl(tpls[i]);
202 this.tpls[tpls[i].id] = tpls[i];
204 this.master = tpls[tpls.length-1];
208 * same as applyTemplate, except it's done to one of the subTemplates
209 * when using named templates, you can do:
211 * var str = pl.applySubTemplate('your-name', values);
214 * @param {Number} id of the template
215 * @param {Object} values to apply to template
216 * @param {Object} parent (normaly the instance of this object)
218 applySubTemplate : function(id, values, parent)
222 var t = this.tpls[id];
226 if(t.test && !t.test.call(this, values, parent)){
230 Roo.log("Xtemplate.applySubTemplate 'test': Exception thrown");
231 Roo.log(e.toString());
237 if(t.exec && t.exec.call(this, values, parent)){
241 Roo.log("Xtemplate.applySubTemplate 'exec': Exception thrown");
242 Roo.log(e.toString());
247 var vs = t.target ? t.target.call(this, values, parent) : values;
248 parent = t.target ? values : parent;
249 if(t.target && vs instanceof Array){
251 for(var i = 0, len = vs.length; i < len; i++){
252 buf[buf.length] = t.compiled.call(this, vs[i], parent);
256 return t.compiled.call(this, vs, parent);
258 Roo.log("Xtemplate.applySubTemplate : Exception thrown");
259 Roo.log(e.toString());
265 compileTpl : function(tpl)
267 var fm = Roo.util.Format;
268 var useF = this.disableFormats !== true;
269 var sep = Roo.isGecko ? "+" : ",";
270 var undef = function(str) {
271 Roo.log("Property not found :" + str);
275 var fn = function(m, name, format, args)
277 //Roo.log(arguments);
278 args = args ? args.replace(/\\'/g,"'") : args;
279 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
280 if (typeof(format) == 'undefined') {
281 format= 'htmlEncode';
283 if (format == 'raw' ) {
287 if(name.substr(0, 4) == 'xtpl'){
288 return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'";
291 // build an array of options to determine if value is undefined..
293 // basically get 'xxxx.yyyy' then do
294 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
295 // (function () { Roo.log("Property not found"); return ''; })() :
300 Roo.each(name.split('.'), function(st) {
301 lookfor += (lookfor.length ? '.': '') + st;
302 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
305 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
310 args = args ? ',' + args : "";
312 if(format.substr(0, 5) != "this."){
313 format = "fm." + format + '(';
315 format = 'this.call("'+ format.substr(5) + '", ';
319 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
323 // called with xxyx.yuu:(test,test)
325 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
327 // raw.. - :raw modifier..
328 return "'"+ sep + udef_st + name + ")"+sep+"'";
332 // branched to use + in gecko and [].join() in others
334 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
335 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
338 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
339 body.push(tpl.body.replace(/(\r\n|\n)/g,
340 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
341 body.push("'].join('');};};");
342 body = body.join('');
345 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
347 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
353 applyTemplate : function(values){
354 return this.master.compiled.call(this, values, {});
359 return this.applyTemplate.apply(this, arguments);
364 Roo.XTemplate.from = function(el){
366 return new Roo.XTemplate(el.value || el.innerHTML);