Playing around with Underscore.js templates

by erichbschulz

HTML

<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>

JavaScript

items = [{
    "id": 28,
    "Title": "Sweden"
}, {
    "id": 56,
    "Title": "USA"
}, {
    "id": 89,
    "Title": "England"
}];

var out = '';
function tableTemplate(cols) {
  var row = '<tr>' + _.map(cols, function(c) {return '<td><%-row.'+c+'%></td>'}) + '</tr>\n' ;
  var th = "<tr><% _.each(col, function(name) { %> <th><%= name %></th> <% }); %></tr>\n";
  var template = '<table><thead>' + _.template(th, {col: cols}) + '</thead>\r' +
   '<tbody><% for(var row in rows) { %>' + row + ' <% }); %></tbody></table>';
  return template
}

var cols = _.keys(items[0]);

var template = tableTemplate(cols);
//out += 'hello world';
$('body').append('<pre>'+ _.escape(template)+ '</pre>');
 
var fish = _.template(template, {rows: items}); 
 
$('body').append('<pre>'+ _.escape(fish)+ '</pre>');