autorenew

ページの追加

Astro i18n Starter で多言語のページを作成する方法はいくつか存在します。

言語ごとにファイルを分けたい場合

pages の下に言語ごとにフォルダを作成し、Astro形式やMarkdown形式でファイルを追加します。

src/pages
├── en/
│   ├── page-1.astro
│   └── page-2.mdx
└── ja/
     ├── page-1.astro
     └── page-2.mdx

以下のページが生成されます

ひとつのファイルで管理したい場合

ページ内の文章量があまり多くない場合は、Astroの動的ルーティング機能を使用して、ひとつのファイルから動的に各言語のページを生成できます。

src/pages
└── [lang]/
    ├── page-1.astro
    └── page-2.astro

ファイルの中で LOCALES オブジェクトをインポートし、Astroの getStaticPaths() 関数により動的ルートを生成します。

---
import { LOCALES } from "@/i18n";

export const getStaticPaths = () =>
  Object.keys(LOCALES).map((lang) => ({
    params: { lang },
  }));
---

以下のページが生成されます

Content Collection を利用したい場合

ブログやニュース等のページをMarkdownファイルで管理したい場合は、Astroのコンテンツコレクション機能を利用できます。

Directory

src/
├── content.config.ts
├── blog/
│   ├── en/
│   │   ├── first-post.md
│   │   └── second-post.md
│   └── ja/
│        ├── first-post.md
│        └── second-post.md
└── pages/[lang]/blog/
     ├── index.astro
     └── [...id].astro

pages/[lang]/blog/[…id].astro

---
import { getCollection } from "astro:content";

export async function getStaticPaths() {
  const posts = await getCollection("blog", ({ data }) => !data.draft)

  return posts.map((post) => {
    const [lang, ...id] = post.id.split("/");
    return { params: { lang, id: id.join("/") || undefined }, props: post };
  });
}
---

詳しくはAstroのドキュメントをご確認ください。

Content Collections | Docs