最近,我在我的Gatsby应用程序中实现了一个国际化功能,但是它应该类似于React应用程序,所以如果您知道React,请告诉我您的经验,谢谢!
为了启用翻译功能,我使用react-i18next。我的文件结构如下所示:
-src
-locale
-en
-translation.js
-zh
-translation.js
-pages
-index.js
-......js因此,我提取了pages文件夹中所有文件的文本,并将它们放在不同的语言文件夹中,当我单击一个按钮来更改语言时,pages中的所有文件都会相应地从不同的语言translation.js文件中找到相应的文本。
但路线一点也不改变。有什么方法可以让我这样做吗:当我改变语言的时候,我的路线会从/en/index /zh/index**?**到/zh/index**?**
我知道我可以制作不同的页面,但我不想这样做,我想保持我当前的处理方式,以将我的文本与应用程序分开。有我可以用的包吗?或者你用什么来处理这个问题?谢谢!
发布于 2020-09-19 10:48:24
改变语言本身不会改变路线。您需要使用gatsby路由器来完成这个任务(via:await navigate('/:lang/path/slug'))。像@jMadelaine说的那样,您不需要更改路由,因为它支持单个页面组件中的多语言url路由。
但是,如果您希望这样做,可以这样做:
您可以使用i18next-browser-languagedetector插件,并且需要在detection.order数组中包含path或querystring,以便在i18next配置中初始化以进行语言检测。https://github.com/i18next/i18next-browser-languageDetector#detector-options
然后,在初始化i18next客户机时,可以使用语言检测器,例如:
import i18next from "i18next"
import LanguageDetector from "i18next-browser-languagedetector"
const detection = {
// order and from where user language should be detected
order: [
"querystring",
"cookie",
"localStorage",
"navigator",
"htmlTag",
"path",
"subdomain",
],
// keys or params to lookup language from
lookupQuerystring: "lng",
lookupCookie: "i18next",
lookupLocalStorage: "i18nextLng",
lookupFromPathIndex: 0,
lookupFromSubdomainIndex: 0,
...
}
i18next.use(LanguageDetector).init({
detection, // <-- passed in here
whitelist: ["en", "es"],
fallbackLng: "en",
resources: i18nResources,
ns: ["translations"],
defaultNS: "translations",
returnObjects: true,
debug: process.env.NODE_ENV === "development",
react: { wait: true },
keySeparator: false,
supportedLngs: ["en", "es"],
lowerCaseLng: true,
})https://stackoverflow.com/questions/63941261
复制相似问题