Adding list and pagination]

This commit is contained in:
Raven Scott
2024-09-16 13:42:27 -04:00
parent 249b793540
commit eaa8eccb79
3 changed files with 110 additions and 21 deletions

47
app.js
View File

@ -62,23 +62,56 @@ function slugToTitle(slug) {
return slug.replace(/-/g, ' ');
}
// Function to load all blog posts
function getAllBlogPosts() {
// Function to load all blog posts with pagination support
function getAllBlogPosts(page = 1, postsPerPage = 5) {
const blogFiles = fs.readdirSync(path.join(__dirname, 'markdown')).filter(file => file.endsWith('.md'));
return blogFiles.map(file => {
// Paginate the results
const totalPosts = blogFiles.length;
const totalPages = Math.ceil(totalPosts / postsPerPage);
const start = (page - 1) * postsPerPage;
const end = start + postsPerPage;
const paginatedFiles = blogFiles.slice(start, end);
const blogPosts = paginatedFiles.map(file => {
const title = file.replace('.md', '').replace(/-/g, ' '); // Keep original casing for title
const slug = titleToSlug(title); // Convert title to slug (lowercase)
// Get the last modified date of the markdown file
const stats = fs.statSync(path.join(__dirname, 'markdown', file));
const lastModifiedDate = new Date(stats.mtime); // Use mtime for last modification time
// Format the date
const formattedDate = lastModifiedDate.toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
return {
title, // Original casing title
slug
slug,
date: formattedDate // Include the formatted date
};
});
return { blogPosts, totalPages };
}
// Home Route (Blog Home)
// Home Route (Blog Home with Pagination)
app.get('/', (req, res) => {
const blogPosts = getAllBlogPosts();
res.render('index', { title: 'Raven Scott Blog', blogPosts });
const page = parseInt(req.query.page) || 1;
const postsPerPage = 5; // Set how many posts to display per page
const { blogPosts, totalPages } = getAllBlogPosts(page, postsPerPage);
res.render('index', {
title: 'Raven Scott Blog',
blogPosts,
currentPage: page,
totalPages
});
});
// About Route