如何在博客文章页面中添加分页功能(Node/Express)

3

我正在构建一个博客网站,当数据库中存储了超过3篇博客文章时,尝试使用分页来导航博客文章的页面。 我正在尝试在单击“较新”或“较旧”按钮时从前端传递数据到后端以控制页面。 我该如何做呢?

我感觉必须以某种方式使用POST方法。

这是我的EJS前端代码。 这些按钮控制帖子的页面:

  <% if(totalItems > 3){ %>
  <div class="page-buttons">
    <form action="/">
      <button type="submit" class="btn btn-outline-info newer-posts">Next</button>

    <button type="submit" class="btn btn-outline-info older-posts">Previous</button>
    </form>

  </div>
  <% } %>

这是后端的路由。

app.get("/", (req, res) => {
  let currentPage = req.query.page || 1;
  let perPage = 3;
  let totalItems;

  Post.find()
    .countDocuments()
    .then(count => {
      totalItems = count;
      Post.find()
        .skip((currentPage - 1) * perPage)
        .limit(perPage)
        .then(posts => {
            res.render("home", {
              posts: posts,
              totalItems: totalItems
            });
        });
    })
});

我希望点击按钮会增加或减少currentPage变量,并从后端渲染正确的博客文章页面。但实际上,它什么都没有做。

任何帮助将不胜感激。

1个回答

2

由于你知道所有项目(博客文章)的总数,你可以进行一些简单的数学计算来确定最后一页。

最初的回答:

const lastPage = Math.ceil(totalItems / perPage);

就像你传递poststotalItems一样,我也会传递currentPagelastPage。我们可以在模板中实现上述数学计算,但为什么要这样做呢?

"Original Answer"的翻译是"最初的回答"

res.render("home", {
    posts,
    currentPage,
    totalItems,
    lastPage
});
// The above notation is shorthand for prop: value

现在,在模板中,我们可以根据传递的变量决定是否显示上一页和下一页按钮。
如果“currentPage”大于1,则必须在第二页或之后,因此显示到当前页面的链接“?page=<%= currentPage - 1 %>”。
如果“currentPage”小于“lastPage”,则说明我们还没有到达最后一页,因此显示到下一页的链接。这将是“?page=<%= currentPage + 1 %>”
这里不需要使用表单,简单的<a>标签就足够了。最初的回答。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接