PDA

View Full Version : Handle multiple dimensional arrays in YAHOO.ext.Template



davidelias
12 Dec 2006, 9:48 AM
I've searched the docs and the forums for this feature, so I tried to implement it.
Something could be wrong, I'm a javascript newbie.



YAHOO.override(YAHOO.ext.DomHelper.Template, {
applyTemplate: function(values){
if(this.compiled){
return this.compiled(values);
}
var empty = '';
var handle_value_depth = function(context, index) {
dot = index.indexOf('.');
if (dot >= 0) {
return handle_value_depth(
context[index.substring(0, dot)],
index.substr(dot+1));
}
return context[index];
}
var fn = function(match, index){
var value = handle_value_depth(values, index);
if(typeof value != 'undefined'){
return value;
}else{
return empty;
}
}
return this.html.replace(this.re, fn);
},

re: /\{([\w\.]+)\}/g,

compile: function() {
var html = this.html;
var re = this.re;
var body = [];
body.push("this.compiled = function(values){ return [");
var result;
var lastMatchEnd = 0;
while ((result = re.exec(html)) != null){
body.push("'", html.substring(lastMatchEnd, result.index), "', ");
body.push("values['", html.substring(result.index+1,re.lastIndex-1).replace(/\./g, "']['"), "'], ");
lastMatchEnd = re.lastIndex;
}
body.push("'", html.substr(lastMatchEnd), "'].join('');};");
eval(body.join(''));
}
});

Now you can do something like this:


var template = new YAHOO.ext.Template(
'<div>'+
'<input> '+
'{product.description} - {product.price}'+
'</div>');
//template.compile();
var values = {
quantity: 5,
product: {
description: 'Some Product',
price: '5.50'
}
}
template.append(cart.dom, values);


Edit changed the regex of the replace inside compile method.

gfraser
25 Jan 2007, 7:24 PM
That's a *really* nice enhancement - it makes dealing with this scenario far, far better! Thanks for sharing this, you've allowed me to significantly clean up some code I was working on and make it far more legible at the same time! :D

vady
7 Mar 2007, 12:29 PM
Good idea!