Kazura
Kazura

Reputation: 93

Handlebars adding items to table template

I would like to add items from a database into a handlebars.js template.

My template looks like this:

<script id="some-template" type="text/x-handlebars-template">
  <table class="mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp">
    <thead>
      <th>Categories</th>
    </thead>
    <tbody>
      {{#categories}}
        <tr>
          <td>{{categoryName}}</td>
        </tr>
      {{/categories}}
    </tbody>
  </table>
</script>

My JS looks like this:

$(document).ready(function() {

  $.getJSON("categories.php", function(data) {

    let source = $("#some-template").html();
    let template = Handlebars.compile(source);

    for (let i = 0; i < data.length; i++) {
      var output = {
        categories: [{
          categoryName: data[i].name
        }]
      };

      console.log(output.categories)
      $("#sampleArea").html(template(output));
    }
  });
});

When i use $("#sampleArea").html(template(output)); it only adds the last item in my database. If i use $("#sampleArea").append(template(output)); however it makes two tables; one for each item in my database.

I also tried:

{{#each categories}}
    <tr>
      <td>{{categoryName}}</td>
    </tr>
{{/each}}

but that didn't work either.

Upvotes: 0

Views: 1151

Answers (1)

osynligsebastian
osynligsebastian

Reputation: 145

You are overwriting the output variable each time you iterate through an item. Try defining the output variable outside the for-loop and push to it inside the loop.

$(document).ready(function() {

  $.getJSON("categories.php", function(data) {

    let source = $("#some-template").html();
    let template = Handlebars.compile(source);
    var output = {
        categories: []
    };

    for (let i = 0; i < data.length; i++) {
      output.categories.push({
        categoryName: data[i].name
      });
    }

    console.log(output.categories)
    $("#sampleArea").html(template(output));
  });
});

Upvotes: 1

Related Questions