Si j'ai 100 produits j'ai pas envie de tous les afficher sur une seule page. J'aimerais rajouter une navigation entre pages de produits
On va rajouter nos boutons pour la navigation
<section class="pagination">
<a href="/?page=1">1</a>
<a href="/?page=2">2</a>
</section>
// controller/shop.js
const ITEMS_PER_PAGE = 2;
exports.getIndex = (req, res, next) => {
const page = req.query.page || 1;
Product.find()
.skip((page - 1) * ITEMS_PER_PAGE)
.limit(ITEMS_PER_PAGE)
.then(products => {
... ...
exports.getIndex = (req, res, next) => {
const page = +req.query.page || 1;
let totalItems;
Product.find()
.countDocuments()
.then(numProducts => {
totalItems = numProducts;
return Product.find()
.skip((page - 1) * ITEMS_PER_PAGE)
.limit(ITEMS_PER_PAGE)
})
.then(products => {
res.render('shop/index', {
prods: products,
pageTitle: 'Shop',
path: '/',
// we pass all the data needed in the view
totalProducts: totalItems,
hasNextPage: ITEMS_PER_PAGE * page < totalItems,
hasPreviousPage: page > 1,
nextPage: page + 1,
previousPaga : page - 1,
lastPage: Math.ceil(totalItems / ITEMS_PER_PAGE)
});
})
// view // index.ejs
<section class="pagination">
<% if (currentPage != 1 && previousPage != 1) { %>
<a href="/?page=1">1</a>
<% } %>
<% if (hasPreviousPage) { %>
<a href="/?page=<%= previousPage %>"><%= previousPage %></a>
<% } %>
<a href="/?page=<%= currentPage %>" class="active"><%= currentPage %></a>
<% if (hasNextPage) { %>
<a href="/?page=<%= nextPage %>"><%= nextPage %></a>
<% } %>
<% if (lastPage != currentPage && nextPage != lastPage) { %>
<a href="/?page=<%= lastPage %>"><%= lastPage %></a>
<% } %>
</section>
exports.getPosts = (req, res, next) => {
const currentPage = req.query.page || 1
let totalItems;
let perPage = 2;
Post.find()
.countDocuments()
.then(count => {
totalItems = count;
return Post.find()
.skip((currentPage - 1) * perPage)
.limit(perPage)
})
.then(posts => {
res.status(200).json({
message: 'Fetched post successfully',
posts: posts,
totalItems: totalItems
})
})
.catch(err => {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
});
}