Grid Loading Data Template

I thought I would share something which in the category of “Little known things which can be done.”

From time to time I’ve wanted to format each grid row using a template function, similar to a loading a dataview. Here’s how:

First create the grid with a single column:

grid = cell.attachGrid()
grid.setHeader(" ");

Then create the template function:

var t = function(o) {
   return '<div>' +
           '<div style="font-weight:bold;text-align:left">'+ o.subject + '</div>' +
           '<div style="height:5px"></div>' +
           '<div style="float:left;padding-bottom:5px;">'+ o.msg_from + '</div><div style="float:right">' + o.dt+ '</div>' +

Here is json data:

d = [
     {"id":"10","msg_from":"Person A","subject":"This is a 1st msg", "dt":"05/01/2015 02:29:58 pm"},
     {"id":"11","msg_from":"Person B","subject":"This is a 2nd msg", "dt":"05/02/2015 04:29:58 pm"},
     {"id":"12","msg_from":"Person B","subject":"This is a 3rd msg", "dt":"05/03/2015 05:29:58 pm"},

Here’s the new prototype which does the magic:

dhtmlXGridObject.prototype.parseTemplate=function(d, f) {
  for (var i=0; i<d.length; i++){
    this.addRow(d[i].id, [f(d[i])])

Now call the prototype:

  grid.parseTemplate(d, t)

Note that the css in the template function is a bit messy. This is a cleaner.

  var t = function(o) {
    return '<div>' +
           '<div style="font-size:90%;float:left;">'+ o.msg_from + '</div>' + 
           '<div style="font-size:90%;float:right">' + o.dt + '</div>' +
           '<div style="clear:both;font-weight:bold;text-align:left;padding-top:2px;padding-bottom:2px">'+ o.subject + '</div>' +