Astro2.0のタグごとのページネーション

作成:
heroimage

タグごとのページも paginate する

ディレクトリとファイルは以下のようにする

├── pages
│   ├── [...page].astro
│   ├── [...slug].astro
│   ├── [tag]
│   │   └── [...page].astro
│   ├── note
│   │   ├── [...slug].astro
│   │   └── index.astro
---
import BaseLayout from "@layouts/BaseLayout.astro";
import Card from "@components/BlogCard.astro";
import CardList from "@components/CardList.astro";
import PageNav from "@components/PageNav.astro";
import Tags from "@components/Tags.astro";
import { getCollection } from "astro:content";
import { BLOG_NAME, BLOG_PAGESIZE } from "@config/config";

export async function getStaticPaths({ paginate }) {
  const allPosts = await getCollection(BLOG_NAME);
  allPosts.sort(
    (a, b) => new Date(b.data.date).valueOf() - new Date(a.data.date).valueOf()
  );
  const allTags = [...new Set(allPosts.map((post) => post.data.tags).flat())];

  return allTags.map((tag) => {
    const filteredPosts = allPosts.filter((post) =>
      post.data.tags?.includes(tag!)
    );
    return paginate(filteredPosts, {
      params: { tag },
      pageSize: BLOG_PAGESIZE,
    });
  });
}
const { page } = Astro.props;
const params = Astro.params;
const nextText = "次の10件";
const prevText = "前の10件";
const pageTitle =
  "[" +
  params.tag +
  "] の付いた記事 " +
  page.currentPage +
  "/" +
  page.lastPage +
  " ページ";
---

<BaseLayout pageTitle={pageTitle}>
  <CardList>
    {page.data.map((post) => <Card entry_name={BLOG_NAME} post={post} />)}
  </CardList>
  <PageNav
    prev={page.url.prev}
    next={page.url.next}
    prev_text={prevText}
    next_text={nextText}
  />
  <hr />
</BaseLayout>