Joe W
Joe W

Reputation: 1567

Using an array to populate Handlebars template

I have a javascript function that takes the total number of items in a list and then divides them based on how many are allowed on a page. I use an array that I populate with a loop based on that number to create my page numbers. This is all for a handlebars template.

My problem is, it doesn't seem like the array is going through the template, but just being put straight into my div, because when inspect the element, there is no anchor tag around either of the numbers

The function:

function GetPages() {

    var TotalItems = 10;
    var NumOnPage = 9;
    var NumPages = Math.ceil(TotalItems / NumOnPage);
    console.log(NumPages);
    var list = [];
    for (var i = 1; i <= NumPages; i++) {
        list.push(i);
    }
    var source = $("#HB-PageTemplate").html();
    var template = Handlebars.compile(source);
    var html = (list);
    $('.Pager').append(html);
}

The Template:

<script id="HB-PageTemplate" type="text/x-handlebars-template">
    {{#each list}}
        <div><a class="pagelink">{{this}}</a></div>
    {{/each}}
</script>

The div:

<div class="Pager"></div>

Upvotes: 0

Views: 578

Answers (1)

Andriy
Andriy

Reputation: 15472

you need to pass list variable to the template by executing template with this list as argument:

function GetPages() {

  var TotalItems = 10;
  var NumOnPage = 9;
  var NumPages = Math.ceil(TotalItems / NumOnPage);
  console.log(NumPages);
  // this will create a range array from 1 to NumPages
  var list = Array.apply(null, Array(NumPages)).map((v, k) => k + 1);

  var source = $("#HB-PageTemplate").html();
  var template = Handlebars.compile(source);

  $('.Pager').html(template({list: list}));
}

plunker: http://plnkr.co/edit/be84uDn8ycBbHn2Bp7FV?p=preview

Upvotes: 1

Related Questions