#pagination
3 messages · Page 1 of 1 (latest)
To add pagination to your Astro blog collection, you can use the paginate function provided by Astro. Here's an example of how you can use it based on the information extracted from the sources:
---
import { paginate } from 'astro/dist/runtime.js'; // Import the paginate function
// Your existing code
import MainLayout from '../../layouts/MainLayout.astro'
import { getCollection } from 'astro:content'
import FormattedDate from '../../components/FormattedDate.astro'
// Filter out content entries with draft: true
const publishedBlogEntries = await getCollection('blog', ({ data }) => {
return data.draft !== true
})
const posts = publishedBlogEntries.sort(
(a, b) => a.data.pubDate.valueOf() - b.data.pubDate.valueOf(),
)
// Pagination
const paginatedPosts = paginate(posts, {pageSize: 5}); // Change 5 to the number of posts you want per page
---
// Now, you can get the paginated posts from your props.
const { page } = Astro.props; // The page prop has everything that you need to render a single page in the collection.
In this example, paginate is a function that takes two arguments: the array of items you want to paginate (in this case, posts), and an options object where you can specify the pageSize (the number of items per page).
The paginate function returns an object that includes the paginated items and some additional properties that you can use for navigation (like currentPage, totalPages, etc.). You can access these properties through the page prop.
Please note that this is a simplified example and you might need to adjust it to fit your specific use case. For more detailed information, you can refer to the Astro documentation (https://docs.astro.build/core-concepts/collections).
Sources:
- Github Issue 501 (https://github.com/withastro/astro/issues/501)
- Github Issue 1004 (https://github.com/withastro/astro/issues/1004)
- Github Issue 2813 (https://github.com/withastro/astro/issues/2813)