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("");
105 doc.documentElement.innerHTML = this.html ;
108 doc = new ActiveXObject('htmlfile');
110 doc.write(this.html);
113 //doc.documentElement.innerHTML = htmlBody
114 var div = doc.documentElement;
119 this.iterChild(div, function(n) {_t.compileNode(n, true); });
121 var tpls = this.tpls;
123 // create a top level template from the snippet..
125 //Roo.log(div.innerHTML);
132 body : div.innerHTML,
145 Roo.each(tpls, function(tp){
147 this.tpls[tp.id] = tp;
150 this.master = tpls[0];
156 compileNode : function(node, istop) {
161 // skip anything not a tag..
162 if (node.nodeType != 1) {
163 if (node.nodeType == 3 && !this.inPre) {
164 // reduce white space..
165 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
188 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
189 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
190 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
191 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
197 // just itterate children..
198 this.iterChild(node,this.compileNode);
202 tpl.value = node.getAttribute('roo-' + tpl.attr);
203 node.removeAttribute('roo-'+ tpl.attr);
204 if (tpl.attr != 'name') {
205 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
206 node.parentNode.replaceChild(placeholder, node);
209 var placeholder = document.createElement('span');
210 placeholder.className = 'roo-tpl-' + tpl.value;
211 node.parentNode.replaceChild(placeholder, node);
214 // parent now sees '{domtplXXXX}
215 this.iterChild(node,this.compileNode);
217 // we should now have node body...
218 var div = document.createElement('div');
219 div.appendChild(node);
221 // this has the unfortunate side effect of converting tagged attributes
222 // eg. href="{...}" into %7C...%7D
223 // this has been fixed by searching for those combo's although it's a bit hacky..
226 tpl.body = div.innerHTML;
234 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
235 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
236 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
241 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
245 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
249 tpl.id = tpl.value; // replace non characters???
265 * Compile a segment of the template into a 'sub-template'
271 compileTpl : function(tpl)
273 var fm = Roo.util.Format;
274 var useF = this.disableFormats !== true;
276 var sep = Roo.isGecko ? "+\n" : ",\n";
278 var undef = function(str) {
279 Roo.debug && Roo.log("Property not found :" + str);
287 var fn = function(m, lbrace, name, format, args)
290 //Roo.log(arguments);
291 args = args ? args.replace(/\\'/g,"'") : args;
292 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
293 if (typeof(format) == 'undefined') {
294 format = 'htmlEncode';
296 if (format == 'raw' ) {
300 if(name.substr(0, 6) == 'domtpl'){
301 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
304 // build an array of options to determine if value is undefined..
306 // basically get 'xxxx.yyyy' then do
307 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
308 // (function () { Roo.log("Property not found"); return ''; })() :
313 Roo.each(name.split('.'), function(st) {
314 lookfor += (lookfor.length ? '.': '') + st;
315 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
318 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
323 args = args ? ',' + args : "";
325 if(format.substr(0, 5) != "this."){
326 format = "fm." + format + '(';
328 format = 'this.call("'+ format.substr(5) + '", ';
332 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
336 // called with xxyx.yuu:(test,test)
338 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
340 // raw.. - :raw modifier..
341 return "'"+ sep + udef_st + name + ")"+sep+"'";
345 // branched to use + in gecko and [].join() in others
347 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
348 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
351 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
352 body.push(tpl.body.replace(/(\r\n|\n)/g,
353 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
354 body.push("'].join('');};};");
355 body = body.join('');
358 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
360 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
367 * same as applyTemplate, except it's done to one of the subTemplates
368 * when using named templates, you can do:
370 * var str = pl.applySubTemplate('your-name', values);
373 * @param {Number} id of the template
374 * @param {Object} values to apply to template
375 * @param {Object} parent (normaly the instance of this object)
377 applySubTemplate : function(id, values, parent)
381 var t = this.tpls[id];
385 if(t.ifCall && !t.ifCall.call(this, values, parent)){
386 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
390 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
397 if(t.execCall && t.execCall.call(this, values, parent)){
401 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
407 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
408 parent = t.target ? values : parent;
409 if(t.forCall && vs instanceof Array){
411 for(var i = 0, len = vs.length; i < len; i++){
413 buf[buf.length] = t.compiled.call(this, vs[i], parent);
415 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
417 //Roo.log(t.compiled);
424 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
429 return t.compiled.call(this, vs, parent);
431 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
433 //Roo.log(t.compiled);
441 applyTemplate : function(values){
442 return this.master.compiled.call(this, values, {});
447 return this.applyTemplate.apply(this, arguments);
452 Roo.DomTemplate.from = function(el){
454 return new Roo.Domtemplate(el.value || el.innerHTML);