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.."></div>
31 <div roo-if="a_variable or condition"></div>
32 <div roo-exec="some javascript"></div>
33 <div roo-name="named_template"></div>
38 Roo.DomTemplate = function()
40 Roo.DomTemplate.superclass.constructor.apply(this, arguments);
47 Roo.extend(Roo.DomTemplate, Roo.Template, {
49 * id counter for sub templates.
53 * flag to indicate if dom parser is inside a pre,
54 * it will strip whitespace if not.
59 * The various sub templates
67 * basic tag replacing syntax
70 * // you can fake an object call by doing this
74 re : /(\{|\%7B)([\w-\.]+)(?:\:([\w\.]*)(?:\(([^)]*?)?\))?)?(\}|\%7D)/g,
75 //re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
77 iterChild : function (node, method) {
79 var oldPre = this.inPre;
80 if (node.tagName == 'PRE') {
83 for( var i = 0; i < node.childNodes.length; i++) {
84 method.call(this, node.childNodes[i]);
92 * compile the template
94 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
101 // covert the html into DOM...
104 doc = document.implementation.createHTMLDocument("");
107 doc = new ActiveXObject('htmlfile');
112 //doc.documentElement.innerHTML = htmlBody
113 var div = doc.documentElement;
114 div.innerHTML = this.html ;
118 this.iterChild(div, function(n) {_t.compileNode(n, true); });
120 var tpls = this.tpls;
122 // create a top level template from the snippet..
124 //Roo.log(div.innerHTML);
131 body : div.innerHTML,
144 Roo.each(tpls, function(tp){
146 this.tpls[tp.id] = tp;
149 this.master = tpls[0];
155 compileNode : function(node, istop) {
160 // skip anything not a tag..
161 if (node.nodeType != 1) {
162 if (node.nodeType == 3 && !this.inPre) {
163 // reduce white space..
164 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
187 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
188 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
189 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
190 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
196 // just itterate children..
197 this.iterChild(node,this.compileNode);
201 tpl.value = node.getAttribute('roo-' + tpl.attr);
202 node.removeAttribute('roo-'+ tpl.attr);
203 if (tpl.attr != 'name') {
204 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
205 node.parentNode.replaceChild(placeholder, node);
208 var placeholder = document.createElement('span');
209 placeholder.className = 'roo-tpl-' + tpl.value;
210 node.parentNode.replaceChild(placeholder, node);
213 // parent now sees '{domtplXXXX}
214 this.iterChild(node,this.compileNode);
216 // we should now have node body...
217 var div = document.createElement('div');
218 div.appendChild(node);
220 // this has the unfortunate side effect of converting tagged attributes
221 // eg. href="{...}" into %7C...%7D
222 // this has been fixed by searching for those combo's although it's a bit hacky..
225 tpl.body = div.innerHTML;
233 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
234 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
235 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
240 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
244 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
248 tpl.id = tpl.value; // replace non characters???
264 * Compile a segment of the template into a 'sub-template'
270 compileTpl : function(tpl)
272 var fm = Roo.util.Format;
273 var useF = this.disableFormats !== true;
275 var sep = Roo.isGecko ? "+\n" : ",\n";
277 var undef = function(str) {
278 Roo.debug && Roo.log("Property not found :" + str);
286 var fn = function(m, lbrace, name, format, args)
289 //Roo.log(arguments);
290 args = args ? args.replace(/\\'/g,"'") : args;
291 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
292 if (typeof(format) == 'undefined') {
293 format = 'htmlEncode';
295 if (format == 'raw' ) {
299 if(name.substr(0, 6) == 'domtpl'){
300 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
303 // build an array of options to determine if value is undefined..
305 // basically get 'xxxx.yyyy' then do
306 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
307 // (function () { Roo.log("Property not found"); return ''; })() :
312 Roo.each(name.split('.'), function(st) {
313 lookfor += (lookfor.length ? '.': '') + st;
314 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
317 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
322 args = args ? ',' + args : "";
324 if(format.substr(0, 5) != "this."){
325 format = "fm." + format + '(';
327 format = 'this.call("'+ format.substr(5) + '", ';
331 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
335 // called with xxyx.yuu:(test,test)
337 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
339 // raw.. - :raw modifier..
340 return "'"+ sep + udef_st + name + ")"+sep+"'";
344 // branched to use + in gecko and [].join() in others
346 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
347 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
350 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
351 body.push(tpl.body.replace(/(\r\n|\n)/g,
352 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
353 body.push("'].join('');};};");
354 body = body.join('');
357 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
359 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
366 * same as applyTemplate, except it's done to one of the subTemplates
367 * when using named templates, you can do:
369 * var str = pl.applySubTemplate('your-name', values);
372 * @param {Number} id of the template
373 * @param {Object} values to apply to template
374 * @param {Object} parent (normaly the instance of this object)
376 applySubTemplate : function(id, values, parent)
380 var t = this.tpls[id];
384 if(t.ifCall && !t.ifCall.call(this, values, parent)){
385 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
389 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
396 if(t.execCall && t.execCall.call(this, values, parent)){
400 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
406 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
407 parent = t.target ? values : parent;
408 if(t.forCall && vs instanceof Array){
410 for(var i = 0, len = vs.length; i < len; i++){
412 buf[buf.length] = t.compiled.call(this, vs[i], parent);
414 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
416 //Roo.log(t.compiled);
423 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
428 return t.compiled.call(this, vs, parent);
430 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
432 //Roo.log(t.compiled);
440 applyTemplate : function(values){
441 return this.master.compiled.call(this, values, {});
446 return this.applyTemplate.apply(this, arguments);
451 Roo.DomTemplate.from = function(el){
453 return new Roo.Domtemplate(el.value || el.innerHTML);