I make an ajax call that returns a dataset in json which looks like this: [URL=”http://imgur.com/HyeSzYb”]http://imgur.com/HyeSzYb
Everything (including the correct column names) has already been taken care of via DB views so I wanted to write a script that just grabs a dataset and spits it out in nicely formatted html. This way the view can be changed (columns added and removed) and the code will not have to be updated. I initially tried to get this to work with mustache but there doesn’t seem to be a simple way of doing it. Right now I just do it in js like this:
[CODE]//Using bootstrap to pretty it up
htmlTableDataset = ‘<table class=”table table-hover table-bordered”>’;
//Get <th> headers from first object in dataset
var htmlTableHeaders = ‘<thead><tr>’;
for (var keyName in dataset[0]){
htmlTableHeaders += ‘<th>’+keyName+'</th>’;
};
htmlTableHeaders += ‘</tr></thead>’;
//Build table body
var htmlTableBody = ‘<tbody>’;
datasetLength = dataset.length;
for (var i=0; i<datasetLength; i++) {
currentRow = dataset[i];
var htmlDatarow = ‘<tr>’;
for (var prop in currentRow){
htmlDatarow += ‘<td>’ + currentRow[prop] + ‘</td>’;
}
htmlDatarow += ‘</tr>’;
htmlTableBody += htmlDatarow;
};
htmlTableBody += ‘</tbody>’;
//Finish table
htmlTableDataset += (htmlTableHeaders + htmlTableBody + ‘</table>’);
$(htmlContainer).html(htmlTableDataset);
This works fine, but I really would like to simplify it further with mustache (if that is possible). The problem is that its an array of objects with multiple properties- can mustache process this in a more efficient way?
edit: I’d also like to add that I am already using mustache in a bunch of other places (code I don’t feel like re-writing with a new engine right now) so if mustache can’t do it I’ll stick to pure js for the time being.