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...
105 doc = document.implementation.createHTMLDocument("");
106 doc.documentElement.innerHTML = this.html ;
107 div = doc.documentElement;
109 // old IE... - nasty -- it causes all sorts of issues.. with
110 // images getting pulled from server..
111 div = document.createElement('div');
112 div.innerHTML = this.html;
114 //doc.documentElement.innerHTML = htmlBody
120 this.iterChild(div, function(n) {_t.compileNode(n, true); });
122 var tpls = this.tpls;
124 // create a top level template from the snippet..
126 //Roo.log(div.innerHTML);
133 body : div.innerHTML,
146 Roo.each(tpls, function(tp){
148 this.tpls[tp.id] = tp;
151 this.master = tpls[0];
157 compileNode : function(node, istop) {
162 // skip anything not a tag..
163 if (node.nodeType != 1) {
164 if (node.nodeType == 3 && !this.inPre) {
165 // reduce white space..
166 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
189 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
190 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
191 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
192 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
198 // just itterate children..
199 this.iterChild(node,this.compileNode);
203 tpl.value = node.getAttribute('roo-' + tpl.attr);
204 node.removeAttribute('roo-'+ tpl.attr);
205 if (tpl.attr != 'name') {
206 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
207 node.parentNode.replaceChild(placeholder, node);
210 var placeholder = document.createElement('span');
211 placeholder.className = 'roo-tpl-' + tpl.value;
212 node.parentNode.replaceChild(placeholder, node);
215 // parent now sees '{domtplXXXX}
216 this.iterChild(node,this.compileNode);
218 // we should now have node body...
219 var div = document.createElement('div');
220 div.appendChild(node);
222 // this has the unfortunate side effect of converting tagged attributes
223 // eg. href="{...}" into %7C...%7D
224 // this has been fixed by searching for those combo's although it's a bit hacky..
227 tpl.body = div.innerHTML;
235 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
236 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
237 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
242 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
246 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
250 tpl.id = tpl.value; // replace non characters???
266 * Compile a segment of the template into a 'sub-template'
272 compileTpl : function(tpl)
274 var fm = Roo.util.Format;
275 var useF = this.disableFormats !== true;
277 var sep = Roo.isGecko ? "+\n" : ",\n";
279 var undef = function(str) {
280 Roo.debug && Roo.log("Property not found :" + str);
288 var fn = function(m, lbrace, name, format, args)
291 //Roo.log(arguments);
292 args = args ? args.replace(/\\'/g,"'") : args;
293 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
294 if (typeof(format) == 'undefined') {
295 format = 'htmlEncode';
297 if (format == 'raw' ) {
301 if(name.substr(0, 6) == 'domtpl'){
302 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
305 // build an array of options to determine if value is undefined..
307 // basically get 'xxxx.yyyy' then do
308 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
309 // (function () { Roo.log("Property not found"); return ''; })() :
314 Roo.each(name.split('.'), function(st) {
315 lookfor += (lookfor.length ? '.': '') + st;
316 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
319 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
324 args = args ? ',' + args : "";
326 if(format.substr(0, 5) != "this."){
327 format = "fm." + format + '(';
329 format = 'this.call("'+ format.substr(5) + '", ';
333 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
336 if (args && args.length) {
337 // called with xxyx.yuu:(test,test)
339 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
341 // raw.. - :raw modifier..
342 return "'"+ sep + udef_st + name + ")"+sep+"'";
346 // branched to use + in gecko and [].join() in others
348 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
349 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
352 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
353 body.push(tpl.body.replace(/(\r\n|\n)/g,
354 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
355 body.push("'].join('');};};");
356 body = body.join('');
359 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
361 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
368 * same as applyTemplate, except it's done to one of the subTemplates
369 * when using named templates, you can do:
371 * var str = pl.applySubTemplate('your-name', values);
374 * @param {Number} id of the template
375 * @param {Object} values to apply to template
376 * @param {Object} parent (normaly the instance of this object)
378 applySubTemplate : function(id, values, parent)
382 var t = this.tpls[id];
386 if(t.ifCall && !t.ifCall.call(this, values, parent)){
387 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
391 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
398 if(t.execCall && t.execCall.call(this, values, parent)){
402 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
408 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
409 parent = t.target ? values : parent;
410 if(t.forCall && vs instanceof Array){
412 for(var i = 0, len = vs.length; i < len; i++){
414 buf[buf.length] = t.compiled.call(this, vs[i], parent);
416 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
418 //Roo.log(t.compiled);
425 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
430 return t.compiled.call(this, vs, parent);
432 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
434 //Roo.log(t.compiled);
442 applyTemplate : function(values){
443 return this.master.compiled.call(this, values, {});
448 return this.applyTemplate.apply(this, arguments);
453 Roo.DomTemplate.from = function(el){
455 return new Roo.Domtemplate(el.value || el.innerHTML);