0

I am trying to populate a table with data returned from an ajax call. I am using handlebars as the templating engine. I am obviously doing this on the client. I found a lot of questions (here, here and here) asking about populating templates from object arrays. I have tried all of them without success. The last version I tried is as follows.

The template is embedded in a script tag.

<script id="resultTableTpl" type="text/template">
<table  class="table table-striped">
  <thead>
    <tr>
      <th>#</th>
      <th>Regd. No.</th>
      <th>Type</th>
    </tr>
  </thead>
  <tbody>
    {{#each this}}
        <tr>
          <td>{{id}}</td>
          <td>{{regd_id}}</td>
          <td>{{type}}</td>
        </tr>
    {{/each}}
  </tbody>
</table>    
</script>

And this is the call to populate the template.

<script>
$("#submitSearch").on('click', function(e) {
    e.preventDefault();
    $.getJSON(...)
    .done(function(data) {
        template = Handlebars.compile($("#resultTableTpl").html());
        $("#myDiv").replaceWith(template(data));
    })
    .fail(function(){
        alert("failure");
    });
});
</script>

The JSON data that is obtained from the ajax call is:

       [ 
        {id: 123, regd_id: "KA-123", type: "3w"}
        , {id: 345, regd_id: "KA-345", type: "4w"}
        , {id: 567, regd_id: "KA-567", type: "5w"}
        ]

This should populate the div myDiv with a table. My test JSON data has an array of three objects. The generated table has empty three rows with three columns. What am I missing? I am using the express flavour of handlebars from exphbs.

Community
  • 1
  • 1
341008
  • 9,862
  • 11
  • 52
  • 84

0 Answers0