i18n - 教程
This tutorial will walk you through the basics of the Docusaurus i18n system.
We will add French translations to a newly initialized English Docusaurus website.
Initialize a new site with npx create-docusaurus@latest website classic
(like this one).
Configure your site
Modify docusaurus.config.js
to add the i18n support for the French language.
Site configuration
Use the site i18n configuration to declare the i18n locales:
export default {
i18n: {
defaultLocale: 'en',
locales: ['en', 'fr', 'fa'],
localeConfigs: {
en: {
htmlLang: 'en-GB',
},
// 如果不需要重写默认值,可以忽略 locale (例如 fr)
fa: {
direction: 'rtl',
},
},
},
};
语言名称会被用于翻译文件的位置以及你的本地化网站的 base URL。 构建所有语言时,只有默认语言才会在 base URL 中省略它的名字。
Docusaurus uses the locale names to provide sensible defaults: the <html lang="...">
attribute, locale label, calendar format, etc. You can customize these defaults with the localeConfigs
.
Theme configuration
Add a navbar item of type localeDropdown
so that users can select the locale they want:
export default {
themeConfig: {
navbar: {
items: [
{
type: 'localeDropdown',
position: 'left',
},
],
},
},
};
You can pass a query parameter that will be appended to the URL when a user changes the locale using the dropdown (e.g. queryString: '?persistLocale=true'
).
This is useful for implementing an automatic locale detection on your server. For example, you can use this parameter to store the user's preferred locale in a cookie.