handlebar example for javascript templating

Handlebar is a logic less javascript templating engine. It’s build on top of another javascript templating tool mushtache. Thus, everything in mushtache is available in Handlebar. Here is an example of using handlebar to dynamically create a html table by parsing a json object.

1. Include the handlebar and jQuery library in the html page.

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

2. The template is included in a script tag with type=”text/x-handlebars-template” to prevent it gets parsed as javascript code.

<script id="table-template" type="text/x-handlebars-template"> 
<table>
    <thead>
        <th>Category</th>
        {{#each this}}
        <th>{{@key}}</th> 
        {{/each}}
    </thead> 
    <tbody> 
        <tr>
              <th>Transportation</th>
              {{#each this}} 
                <td>{{this.auto_transport}}</td>
              {{/each}} 
       </tr>
       <tr>
              <th>Food</th>
              {{#each this}} 
                <td>{{this.food}}</td>
              {{/each}} 
       </tr>
    </tbody> 
</table> 
</script>

3. Using handlebar to render the above template into a html table and append it to the body.

<script type="text/javascript">
var source = $("#table-template").html(); 
var template = Handlebars.compile(source); 
var data = {
  "2014-02": {
    "auto_transport": 104.5,
    "food": 412.68
  },
  "2014-03": {
    "auto_transport": 433.76,
    "food": 496.02
  },
  "2014-04": {
    "auto_transport": 211,
    "food": 348.71
  },
  "2014-05": {
    "auto_transport": 566.13,
    "food": 380.09,
  }
};
$('body').append(template(data));
</script>

4. The html result:

Category 2014-02 2014-03 2014-04 2014-05
Transportation 104.5 433.76 211 566.13
Food 412.68 496.02 348.71 380.09

Search within Codexpedia

Custom Search

Search the entire web

Custom Search