How to show number of pages in handlebars paging?

Asked

Viewed 206 times

1

This is my code to calculate the number of pages, here is calculating everything correctly, already tested.

app.get("/page/:page", (req, res) => {
    var perPage = 3
        , page = Math.max(0, req.params.page)

    Postagem.find().populate("categoria")
        .limit(perPage)
        .skip(perPage * (page - 1))
        .sort({
            data: "desc"
        })
        .exec(function (err, postagens) {
            Postagem.count().exec(function (err, count) {
                res.render('index', {
                    postagens: postagens,
                    page: page,
                    pages: count / perPage
                })
            })
        })
})

Below my handlebars, I’m trying to pass the number of calculated pages to create but nothing appears:

<nav aria-label="Page navigation example">
    <ul class="pagination">
        <li class="page-item"><a class="page-link text-danger" href="#">Previous</a></li>
        {{#each pages}}
        <li class="page-item"><a class="page-link text-danger" href="/{{page}}">{{pages}}</a></li>
        {{/each}}
        <li class="page-item"><a class="page-link text-danger" href="/#">Next</a></li>
    </ul>
</nav>

But nothing appears, I’ve tried to research how to do this but I haven’t found anywhere... Does anyone know how I can solve?

1 answer

2

You can take a look at a library called "Handlerbars Paginate helper". To install, you do the following:

npm install handlebars-paginate

You register this library as a helper

var Handlebars = require('handlebars');
var paginate = require('handlebars-paginate');

Handlebars.registerHelper('paginate', paginate);

And then pass an object with the pagination data to your template

 pagination: {
    page: 4,       // Pagina atual
    pageCount: 10  // Total paginas
  }

Inside the template, the layout would look like this:

<div class="pagination pagination-centered">
  <ul>
    {{#paginate pagination type="first"}}
      <li {{#if disabled}}class="disabled"{{/if}}><a href="?p={{n}}">First</a></li>
    {{/paginate}}
    {{#paginate pagination type="previous"}}
      <li {{#if disabled}}class="disabled"{{/if}}><a href="?p={{n}}">Prev</a></li>
    {{/paginate}}
    {{#paginate pagination type="middle" limit="7"}}
      <li {{#if active}}class="active"{{/if}}><a href="?p={{n}}">{{n}}</a></li>
    {{/paginate}}
    {{#paginate pagination type="next"}}
      <li {{#if disabled}}class="disabled"{{/if}}><a href="?p={{n}}">Next</a></li>
    {{/paginate}}
    {{#paginate pagination type="last"}}
      <li {{#if disabled}}class="disabled"{{/if}}><a href="?p={{n}}">Last</a></li>
    {{/paginate}}
  </ul>
</div>

More information:

https://github.com/olalonde/handlebars-paginate http://syskall.com/pagination-with-handlebars/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.