Handlebars: Create a table

by Arvind Pal

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.10/handlebars.min.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<h2>Handlebars template to populate a table</h2>

<h3>People</h3>
<div id="people"></div>

<h3>Smart Phones</h3>
<div id="smartphones"></div>

<!-- The script element is used to define the Handlebars template -->
<script type="text/x-handlebars-template" id="tableTemplate">
<table>
<thead>
  <tr>
    {{#each array.[0]}}
      <th>{{@key}}</th>
    {{/each}}
  </tr>
</thead>
<tbody>
  {{#each array}}
    <tr>
    	{{#each this}}
        <td>{{this}}</td>
      {{/each}}
    </tr>
  {{/each}}
</tbody>
</table>
</script>

<div style="position: absolute;bottom: 5px;">
Read about this Fiddle at: <a href="http://jsdev.wikidot.com/howto:12" target="_blank">How To: Handlebars - Create Table element</a>
</div>

CSS

table {
  width: 100%;
}

table, th, td {
  border: 1px solid lightgrey;
  border-collapse: collapse;
}

th, td {
  padding: 2px 4px;
}

JavaScript

$(function () {
  // Get the text for the Handlebars template from the script element.
  var templateText = $("#tableTemplate").html();
  
  // Compile the Handlebars template.
  var tableTemplate = Handlebars.compile(templateText);
  console.log("tableTemplate", tableTemplate)

	// Define an array of people.
  var people = [
    { "Id": 1, "First Name": "Anthony", "Last Name": "Nelson", "Age": 25 },
    { "Id": 2, "First Name": "Helen", "Last Name": "Garcia", "Age": 32 },
    { "Id": 3, "First Name": "John", "Last Name": "Williams", "Age": 48 }
  ];
  
  // Evaluate the template with an array of people and set the HTML
  // for the people table.
  $("#people").html(tableTemplate({ array: people }));
  
  // Deine an array of smart phones.
  var smartPhones = [
  	{ "Manufacturer": "Apple", "Phone": "iPhone", "Operating System": "iOS" },
    { "Manufacturer": "Samsung", "Phone": "Galaxy", "Operating System": "Android" },
    { "Manufacturer": "Nokia", "Phone": "Lumia", "Operating System": "Windows" }
  ];
  
  // Evaluate the same table template with an array of smart phoes and set the HTML
  // for the smartphones table.
  $("#smartphones").html(tableTemplate({ array: smartPhones }));
});