I needed to bind some data to a table. So I built a little script that does it. I simple create the rows template:
<table id="template_container" style="display:none;"> <tr><td id="row1"></td><td><span id="row2"></span></td><td id="row3"></td></tr></table>
The id inside the template identifies the column that I want to bind.
I also need to create the output container:
<table id="template_output" border="1"></table>
So my datasource looks like this:
var data = {result:[{row1:"Bruno", row2:"Ricardo", row3:"Figueiredo"}, {row1:"Sandra", row2:"Isabel", row3:"Lourenço"}]};
Each property name on the object is the id of the column.
Then, all i need to do is bind:
var t = new Template($("template_container"));t.set_data(data.result);t.bind($("template_output"));
or inline:
new Template($("template_container"), data.result, $("template_output")).bind();
So there you have it.
Source code:
var Template = new Class({ initialize: function() { $each(arguments, function(argument, idx){ if (idx == 0) this._template = $(argument).getFirst(); if (idx == 1) this._data = argument; if (idx == 2) this._container = $(argument); }, this); }, set_data: function(data) { this._data = data; }, bind: function(htmlElement) { this._parseData(this._data, htmlElement || this._container); }, _parseData: function(data, container) { if(data.forEach) { data.forEach(function(row){ var line = this._template.clone(); for (var column in row) { this._setDataContainer(line, column, row[column]); } line.removeAttribute("id"); line.style.display = ""; container.adopt(line); }, this); } }, _setDataContainer:function(line, dataID, data) { $each(line.childNodes, function(element){ if (element.id && element.id == dataID) { element.appendText(data); element.removeAttribute("id"); } else if (element.childNodes) { this._setDataContainer(element, dataID, data); } }, this); }, _isArray: function(object) { return (object.constructor.toString().indexOf("Array")> 0) }});