[Milestone task]: 静的ページ部分の実装方法の検討
Opened this issue · 4 comments
nkte8 commented
How it would to do to accomplish?
Astroでi18nを実装するにあたって、どのようにページの生成を行うかを検討する
静的ページ部分、具体的にはsrc/pages/*.astro
ファイルの箇所についての実装を検討する
What it should do to accomplish?
具体的な実装方法の考案・提示
nkte8 commented
ルーティング方法について
Astroにおいてはディレクトリ型ルーティングを採用しているため、これを用いる
langCodeの取得はURLのPathから判定する
export function getLanguageFromURL(pathname: string) {
const langCodeMatch = pathname.match(/\/([a-z]{2}-?[a-z]{0,2})\//)
return langCodeMatch ? langCodeMatch[1] : "ja"
}
参考:
https://github.com/withastro/docs/blob/main/src/util.ts
https://route360.dev/ja/post/astro-i18n/
nkte8 commented
[slug].astro について
OGP生成ページ astro/src/pages/posts/[slug].astro
についてはOGPの表示や、共有される前提が伴うため別枠で考えたほうがいいため、Issueを別途切る
nkte8 commented
実装について例を作成してみた
https://github.com/nkte8/skyshare/tree/feature/issue_91_redirect_to_lang
実装の詳細
languageコードがない箇所に対してはリクエストヘッダを参照して、languageコードを設定しています。
i18ntest.astro
---
export const prerender = false
import { baseurl } from "@/env/envs"
let lang = Astro.request.headers.get("Accept-Language")
if (lang !== null || lang === "") {
lang = "en"
}
const newUrl = `${baseurl}${lang}${Astro.url.pathname}`
return Astro.redirect(newUrl)
---
これらが以下の静的ページへリダイレクトします。
静的サイトはコンテンツコレクションを参照し、自動で生成されます。
[lang]/i18ntest.astro
---
import { getEntry, getCollection } from "astro:content"
import version from "@/env/version"
import Pagelayout from "@/layouts/Pagelayout.astro"
const { lang } = Astro.params
export const getStaticPaths = async () => {
const allBlogPosts = await getCollection("document") // <---- documentコレクションの情報を一括取得
return allBlogPosts.map(entry => { // <-- return [ { params: { lang: "hoge" }, { params: { lang: "fuga" } }]
return { params: { lang: entry.slug } }
})
}
...
const page = await getEntry("document", lang) // <---- 参照されたlangのエントリーがloadされる
...
const { Content } = await page.render()
---
...
<Content /> </*----- レンダリング箇所 */>
...
nkte8 commented
上記の例ではコレクション側に言語を入れているので、言語をコレクションとしてページを生成することを考えたほうがいいかもしれない
→ そうなった場合にどういう実装になる?