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...
102 var doc = document.implementation.createHTMLDocument("");
103 doc.documentElement.innerHTML = htmlBody
104 var div = doc.documentElement;
105 div.innerHTML = this.html ;
109 this.iterChild(div, function(n) {_t.compileNode(n, true); });
111 var tpls = this.tpls;
113 // create a top level template from the snippet..
115 //Roo.log(div.innerHTML);
122 body : div.innerHTML,
135 Roo.each(tpls, function(tp){
137 this.tpls[tp.id] = tp;
140 this.master = tpls[0];
146 compileNode : function(node, istop) {
151 // skip anything not a tag..
152 if (node.nodeType != 1) {
153 if (node.nodeType == 3 && !this.inPre) {
154 // reduce white space..
155 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
178 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
179 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
180 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
181 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
187 // just itterate children..
188 this.iterChild(node,this.compileNode);
192 tpl.value = node.getAttribute('roo-' + tpl.attr);
193 node.removeAttribute('roo-'+ tpl.attr);
194 if (tpl.attr != 'name') {
195 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
196 node.parentNode.replaceChild(placeholder, node);
199 var placeholder = document.createElement('span');
200 placeholder.className = 'roo-tpl-' + tpl.value;
201 node.parentNode.replaceChild(placeholder, node);
204 // parent now sees '{domtplXXXX}
205 this.iterChild(node,this.compileNode);
207 // we should now have node body...
208 var div = document.createElement('div');
209 div.appendChild(node);
211 // this has the unfortunate side effect of converting tagged attributes
212 // eg. href="{...}" into %7C...%7D
213 // this has been fixed by searching for those combo's although it's a bit hacky..
216 tpl.body = div.innerHTML;
224 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
225 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
226 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
231 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
235 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
239 tpl.id = tpl.value; // replace non characters???
255 * Compile a segment of the template into a 'sub-template'
261 compileTpl : function(tpl)
263 var fm = Roo.util.Format;
264 var useF = this.disableFormats !== true;
266 var sep = Roo.isGecko ? "+\n" : ",\n";
268 var undef = function(str) {
269 Roo.debug && Roo.log("Property not found :" + str);
277 var fn = function(m, lbrace, name, format, args)
280 //Roo.log(arguments);
281 args = args ? args.replace(/\\'/g,"'") : args;
282 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
283 if (typeof(format) == 'undefined') {
284 format = 'htmlEncode';
286 if (format == 'raw' ) {
290 if(name.substr(0, 6) == 'domtpl'){
291 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
294 // build an array of options to determine if value is undefined..
296 // basically get 'xxxx.yyyy' then do
297 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
298 // (function () { Roo.log("Property not found"); return ''; })() :
303 Roo.each(name.split('.'), function(st) {
304 lookfor += (lookfor.length ? '.': '') + st;
305 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
308 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
313 args = args ? ',' + args : "";
315 if(format.substr(0, 5) != "this."){
316 format = "fm." + format + '(';
318 format = 'this.call("'+ format.substr(5) + '", ';
322 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
326 // called with xxyx.yuu:(test,test)
328 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
330 // raw.. - :raw modifier..
331 return "'"+ sep + udef_st + name + ")"+sep+"'";
335 // branched to use + in gecko and [].join() in others
337 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
338 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
341 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
342 body.push(tpl.body.replace(/(\r\n|\n)/g,
343 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
344 body.push("'].join('');};};");
345 body = body.join('');
348 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
350 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
357 * same as applyTemplate, except it's done to one of the subTemplates
358 * when using named templates, you can do:
360 * var str = pl.applySubTemplate('your-name', values);
363 * @param {Number} id of the template
364 * @param {Object} values to apply to template
365 * @param {Object} parent (normaly the instance of this object)
367 applySubTemplate : function(id, values, parent)
371 var t = this.tpls[id];
375 if(t.ifCall && !t.ifCall.call(this, values, parent)){
376 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
380 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
387 if(t.execCall && t.execCall.call(this, values, parent)){
391 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
397 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
398 parent = t.target ? values : parent;
399 if(t.forCall && vs instanceof Array){
401 for(var i = 0, len = vs.length; i < len; i++){
403 buf[buf.length] = t.compiled.call(this, vs[i], parent);
405 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
407 //Roo.log(t.compiled);
414 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
419 return t.compiled.call(this, vs, parent);
421 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
423 //Roo.log(t.compiled);
431 applyTemplate : function(values){
432 return this.master.compiled.call(this, values, {});
437 return this.applyTemplate.apply(this, arguments);
442 Roo.DomTemplate.from = function(el){
444 return new Roo.Domtemplate(el.value || el.innerHTML);