Adding list and pagination]
This commit is contained in:
47
app.js
47
app.js
@ -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
|
||||
|
Reference in New Issue
Block a user