0

我正在尝试使用 handlebars-paginate 中间件对我的记录进行分页以实现此目的。我希望能够每页显示 20 条记录,我已经完成了以下操作:

在入口点js(app.js)里面,我注册了这个助手Handlebars.registerHelper('paginate', paginate);

我的控制器

const perPage = 20
const page = req.query.p

     Customer.find({})
            .skip((perPage * page) - perPage)
            .limit(perPage)
            .lean()
        .exec(function (err, customers) {
            Customer.countDocuments().exec(function (err, count) {
                if (err) {
                    req.flash('error_msg', 'Something happened while trying to process this request. Please try again...')
                    return res.redirect('/account/dashboard')
                }

                res.render('restricted/dashboard', {
                    layout: 'dashboard_layout',
                    pagination: {
                        page: req.query.p || 1,
                        pageCount: perPage
                    },
                    customers,
                    page_title: 'Dashboard'
                })
            })
        })

My HandleBar 查看分页区域

<div class="pagination pagination-centered">
            <ul class="paginate">
                {{#paginate pagination type="first"}}
                    <li {{#if disabled}} class="pageNumber disabled" {{/if}}><a href="?p={{n}}">First</a></li>
                {{/paginate}}

                {{#paginate pagination type="previous"}}
                    <li {{#if disabled}} class="pageNumber disabled" {{/if}}><a href="?p={{n}}">Prev</a></li>
                {{/paginate}}

所以我注意到,当其他页面没有记录时,即使没有记录,仍然有一些分页链接显示。我附上了截图在此处输入图像描述

                {{#paginate pagination type="middle" limit=pagination.pageCount}}
                    <li {{#if active}} class="pageNumber active" {{/if}}><a href="?p={{n}}">{{n}}</a></li>
                {{/paginate}}
                
                {{#paginate pagination type="next"}}
                    <li {{#if disabled}} class="pageNumber disabled" {{/if}}><a href="?p={{n}}">Next</a></li>
                {{/paginate}}

                {{#paginate pagination type="last"}}
                    <li {{#if disabled}}class="pageNumber disabled" {{/if}}><a href="?p={{n}}">Last</a></li>
                {{/paginate}}
            </ul>
        </div>

在此处输入图像描述

谁能指出我需要做什么才能使那些没有记录的额外链接不显示?

4

1 回答 1

1

When rendering the handlebars template, you're using perPage constant, which is 20, as pageCount

   pageCount: perPage

Then in the handlebars template :

   {{#paginate pagination type="middle" limit=pagination.pageCount}}

That's why you have 20 pages all the time.

Because you already count the number of document, the page limit should be: Math.ceil(totalDocument/perPage)

In your code, replace :

 pageCount: perPage

by :

pageCount : Math.ceil(count/perPage)
于 2021-05-08T10:27:34.547 回答