言語スイッチャー
Methanol の多言語対応はディレクトリ単位で管理されます。ディレクトリ内の index.mdx に lang プロパティが設定されている場合、そのディレクトリは独立した言語エントリとして識別されます。
テンプレート内では、以下の情報を利用可能です。
ctx.languages: 定義されているすべての言語エントリのリスト。ctx.language: 現在表示中のページに対応するアクティブな言語エントリ(設定がない場合はnull)。
各エントリには、routePath, routeHref, label, code などのプロパティが含まれます。
<select> タグによるシンプルなスイッチャーの実装
const LanguageSwitch = ({ ctx }) => {
const languages = Array.isArray(ctx.languages) ? ctx.languages : []
if (!languages.length) return null
const currentHref = ctx.language?.routeHref || null
return (
<select
aria-label="Select language"
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 = Array.isArray(ctx.languages) ? ctx.languages : []
if (!languages.length) return null
const currentHref = ctx.language?.routeHref
return (
<nav aria-label="Languages">
{languages.map((lang) => (
<a href={lang.routeHref} aria-current={lang.routeHref === currentHref ? 'page' : null}>
{lang.label}
</a>
))}
</nav>
)
}
実装のポイント
- リンク先には必ず
routeHrefを使用してください(site.baseの設定が自動的に反映されます)。 - 各言語のルートディレクトリに
isRoot: trueを設定することで、言語ごとに独立したナビゲーションツリーを構築できます。