From ea0c94d8e904fcc193df44940698e3f7c30d4938 Mon Sep 17 00:00:00 2001 From: Daisuke Date: Sat, 17 May 2025 21:22:44 +0900 Subject: [PATCH] Add dynamic pagination for blog posts --- src/pages/blog.astro | 32 --------- src/pages/blog/[...page].astro | 126 +++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+), 32 deletions(-) delete mode 100644 src/pages/blog.astro create mode 100644 src/pages/blog/[...page].astro diff --git a/src/pages/blog.astro b/src/pages/blog.astro deleted file mode 100644 index a48cbe4..0000000 --- a/src/pages/blog.astro +++ /dev/null @@ -1,32 +0,0 @@ ---- -import { getCollection } from "astro:content"; -import BaseLayout from "../layouts/BaseLayout.astro"; -import BlogPost from "../components/BlogPost.astro"; - -const allPosts = await getCollection("blog"); -const pageTitle = "Latest Posts"; ---- - - - -
- { - allPosts.map((post: any) => ( - - )) - } -
-
diff --git a/src/pages/blog/[...page].astro b/src/pages/blog/[...page].astro new file mode 100644 index 0000000..c5b361c --- /dev/null +++ b/src/pages/blog/[...page].astro @@ -0,0 +1,126 @@ +--- +import { getCollection } from "astro:content"; +import BaseLayout from "../../layouts/BaseLayout.astro"; +import BlogPost from "../../components/BlogPost.astro"; + +type Page = { + data: T[]; + currentPage: number; + lastPage: number; + url: { + current: string; + first?: string; + prev?: string; + next?: string; + last?: string; + }; +}; + +type BlogPostEntry = { + id: string; + data: { + title: string; + pubDate: Date; + }; +}; + +interface Props { + page: Page; +} + +export async function getStaticPaths({ + paginate +} : { + paginate: (data: any[], options?: { pageSize?: number; params?: Record; props?: Record }) => any; +}) { + const allPosts = await getCollection("blog"); + + allPosts.sort( + (a, b) => new Date(b.data.pubDate).getTime() - new Date(a.data.pubDate).getTime() + ); + + return paginate( + allPosts, + { + pageSize: 6, + } + ); +} + +const { page } = Astro.props as Props; +const pageTitle = "Articles"; +--- + + + + +
+ { + page.data.map((post) => ( + + )) + } +
+ + +
-- 2.49.1