How To: Handlebars - Create Table element

Here is a Handlebars template for creating a table element based on any array of JSON objects:

<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>
  1. {{#each array.[0]}} gets the first JSON object in the array and iterates over the object's attributes.
  2. {{@key}} renders the object's attribute name.
  3. {{#each array}} iterates over each JSON object in the array.
  4. {{#each this}} iterates over each attribute in the current object.
  5. {{this}} renders the value for the current attribute.

Example

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License