國際化
在你的文件中支援多種語言
開始之前
Fumadocs 不是一個功能齊全的 i18n 函式庫,它只管理自己的元件和工具程式。
你可以使用其他函式庫,如 next-intl,用於應用程式的其餘部分。 閱讀 Next.js 文件,了解更多關於在 Next.js 中實作 I18n 的資訊。
手動設定
在一個檔案中定義 i18n 設定,我們將在本指南中使用 @/ilb/i18n
匯入它。
將其傳遞給來源載入器。
import { i18n } from '@/lib/i18n';
import { loader } from 'fumadocs-core/source';
export const source = loader({
i18n,
// other options
});
並更新 Fumadocs UI 佈局選項。
import { i18n } from '@/lib/i18n';
import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared';
export function baseOptions(locale: string): BaseLayoutProps {
return {
i18n,
// different props based on `locale`
};
}
中介軟體
建立一個將使用者重導向到適當語言環境的中介軟體。
{
"file": "../../examples/i18n/middleware.ts",
"codeblock": {
"lang": "ts",
"meta": "title=\"middleware.ts\""
}
}
查看中介軟體了解可自訂選項。
請注意,這是可選的,你也可以使用自己的中介軟體或 i18n 函式庫提供的中介軟體。
路由
建立一個 /app/[lang]
資料夾,並將所有檔案(例如 page.tsx
、layout.tsx
)從 /app
移動到該資料夾。
將根提供者包裝在 I18nProvider
中,並向其提供可用語言和翻譯。
請注意,預設情況下只提供英文翻譯。
import { RootProvider } from 'fumadocs-ui/provider';
import { I18nProvider, type Translations } from 'fumadocs-ui/i18n';
const cn: Partial<Translations> = {
search: 'Translated Content',
// other translations
};
// available languages that will be displayed on UI
// make sure `locale` is consistent with your i18n config
const locales = [
{
name: 'English',
locale: 'en',
},
{
name: 'Chinese',
locale: 'cn',
},
];
export default async function RootLayout({
params,
children,
}: {
params: Promise<{ lang: string }>;
children: React.ReactNode;
}) {
const lang = (await params).lang;
return (
<html lang={lang}>
<body>
<I18nProvider
locale={lang}
locales={locales}
translations={{ cn }[lang]}
>
<RootProvider>{children}</RootProvider>
</I18nProvider>
</body>
</html>
);
}
傳遞語言環境
在你的頁面和佈局中將語言環境傳遞給 Fumadocs。
搜尋
在你的搜尋解決方案上設定 i18n。
撰寫文件
導航
Fumadocs 只處理其自己的佈局(例如側邊欄)的導航。
對於其他地方,你可以使用 useParams
鉤子從 URL 取得語言環境,並將其新增到 href
。
import Link from 'next/link';
import { useParams } from 'next/navigation';
const { lang } = useParams();
return <Link href={`/${lang}/another-page`}>This is a link</Link>;
另外,fumadocs-core/dynamic-link
元件支援動態 hrefs,你可以使用它來新增語言環境前綴。
這對於 Markdown/MDX 內容很有用。
import { DynamicLink } from 'fumadocs-core/dynamic-link';
<DynamicLink href="/[lang]/another-page">This is a link</DynamicLink>