Skip to content

Instantly share code, notes, and snippets.

@steida
Created March 26, 2009 03:03
Show Gist options
  • Save steida/85840 to your computer and use it in GitHub Desktop.
Save steida/85840 to your computer and use it in GitHub Desktop.
// template based on fast string building - proposal
// Daniel Steigerwald - MIT Licensed
var Template = new Class({
Implements: [Events, Options],
options: {
data: null, // datasource
mapper: $empty // custom mapper function, has to return hash. Key is className, value is same hash as for Element.set
},
initialize: function(element, options) {
this.element = $(element);
this.setOptions(options);
},
databind: function() {
if (!this.stringTemplate) this.prepareStringTemplate();
var html = [];
$splat(this.options.data).each(function(item) {
var data = this.options.mapper(item), str = this.stringTemplate;
for (var k in data) {
var data2 = data[k];
for (var k2 in data2) str = str.split('$' + k + '.' + k2 + '$').join(data2[k2]);
}
html.push(str);
}, this);
this.element.set('html', html.join(''));
},
prepareStringTemplate: function() {
$H(this.options.mapper($splat(this.options.data)[0])).each(function(v, k) {
var el = this.element.getElement('.' + k);
$H(v).each(function(v2, k2) {
el.set(k2, ['$', k, '.', k2, '$'].join(''));
});
}, this);
this.stringTemplate = this.element.get('html');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment