言語スイッチャー
Methanol の多言語対応は、ディレクトリ構造に基づいています。ディレクトリ内の index.mdx のフロントマターに lang プロパティが設定されている場合、そのディレクトリは言語のエントリポイントとして識別されます。
テーマのテンプレートでは、言語に関する以下のプロパティを利用可能です。
ctx.languages: 識別されたすべての言語エントリポイントのリスト。ctx.language: 現在のページに対応する言語エントリポイント(存在しない場合はnull)。
各エントリには、routePath、routeHref、label、code が含まれます。
ドロップダウン形式のスイッチャー
<select> 要素を使用した標準的な実装例です。
const LanguageSwitch = ({ ctx }) => {
const languages = ctx.languages || []
if (languages.length === 0) return null
const currentHref = ctx.language?.routeHref
return (
<select
aria-label="言語を選択"
onchange="location.href=this.value"
value={currentHref || undefined}
>
{languages.map((lang) => (
<option value={lang.routeHref} selected={lang.routeHref === currentHref ? true : null}>
{lang.label}
</option>
))}
</select>
)
}
リンクリスト形式のスイッチャー
ヘッダーやフッターに適した、リンクを並べる形式の実装例です。
const LanguageLinks = ({ ctx }) => {
const languages = ctx.languages || []
if (languages.length === 0) return null
const currentHref = ctx.language?.routeHref
return (
<nav aria-label="言語選択">
{languages.map((lang) => (
<a href={lang.routeHref} aria-current={lang.routeHref === currentHref ? 'page' : null}>
{lang.label}
</a>
))}
</nav>
)
}
実装のポイント
- URL の扱い: リンク先には必ず
routeHrefを使用してください。これにより、ベースパスの設定が正しく反映されます。 - ルートスコープ: 各言語のエントリポイントで
isRoot: trueを設定することが一般的です。これにより、言語ごとに独立したナビゲーションツリーを維持できます。