【问题标题】:How to translate location URL when changing language?更改语言时如何翻译位置 URL?
【发布时间】:2020-12-20 02:34:59
【问题描述】:

我目前在网站的本地化过程中遇到了障碍。使用 i18next,我们所有的路由都会被翻译,并且默认语言会从 URL 中删除语言环境路径。

换句话说:
/accueil -> /en/home
/produits -> /en/products
等等……

我的问题是当我更改语言时,url 不跟随(这是可以预料的,因为 i18next 不直接与 react-router 对话)。

i18下一个配置:

i18n
  .use(detector)
  .use(initReactI18next)
  .init({
    whitelist: ['fr', 'en'],
    fallbackLng: 'fr',
    defaultNS: 'common',

    detection: {
      lookupFromPathIndex: 0,
      checkWhitelist: true
    },

    interpolation: {
      escapeValue: false
    },

    resources: {
      en: {
        routes: enRoutes,
        [...]
      },
      fr: {
        routes: frRoutes,
        [...]
      }
    }
  });

fr/routes.json:

{
  "home": "/accueil",
  "products": "/produits",
  [...]
}

en/routes.json:

{
  "home": "/en/home",
  "products": "en/products",
  [...]
}

app.jsx 中的路由器部分:

<Router forceRefresh>
  <Switch>
    <Route path={`/:locale(en|fr)?${t('routes:home')}`} component={HomeComponent} />
    <Route path={`/:locale(en|fr)?${t('routes:products')}`} component={ProductsComponent} />
  </Switch>
</Router>

通过以下配置,当调用 i18n.changeLanguage 时,页面呈现没有问题并且很容易翻译,但 url 不会随之改变。我到处搜索,似乎找不到在语言更改后翻译网址的首选方法。

我还想处理用户直接在浏览器 url 字段中手动更改语言环境的情况。

我已经尝试在 i18next 中更新“languageChanged”事件的 url,但是找到当前页面的键会增加很多复杂性。

提前感谢您提供的任何帮助。

【问题讨论】:

  • 你的Link标签呢?他们的道路也需要改变吗?你确定它们也在改变吗?
  • 是的,它们也发生了变化,我的问题确实发生在 i18n.changeLanguage() 被调用的那一刻。我正在考虑使用自定义更改语言功能,在触发语言更改之前动态找到路由的键,然后使用所述键进行重定向。
  • 不能像this 这样的东西就够了吗?我们确实使用我们自己的自定义钩子构建了一个没有任何库的具有国际化的应用程序。无论如何,它提供了什么好处?
  • 本地化 url 对 SEO 很重要,翻译不是问题,是 URL 的本地化。
  • this 是你想要的吗?

标签: react-router localization internationalization i18next react-i18next


【解决方案1】:

我终于找到了一个简单干净的方法来改变路线,同时也改变语言。

  const changeLanguage = (nextLanguage) => {
    const routes = i18n.getResourceBundle(i18n.language, 'routes');
    const currentPathname = window.location.pathname.replace(/\/+$/, '');
    const currentRouteKey = Object.keys(routes).find((key) => routes[key] === currentPathname);

    window.location.replace(t(`routes:${currentRouteKey}`, { lng: nextLanguage }));
  };

我还需要更改 i18next 检测选项,如下所示:

detection: {
  order: ['path', ...otherMethods]
  lookupFromPathIndex: 0,
  checkWhitelist: true
},

我现在可以在任何地方安全地调用这个 changeLanguage 包装器,它会处理语言更改(如果它不是 URL 的一部分,则默认设置)和路由更改。

【讨论】:

  • 你好,程序员。我只是偶然发现了这个,它只有20天。所以当熨斗很热的时候。让我请你提供一个要点来进一步解释,你做了什么以及如何做的?会赞成;-)
  • 您好,我不是专家,但我很乐意为您提供帮助并提供更准确的解释,说明我是如何解决我的问题的。所以我会尝试一下,但是任何关于我如何能帮助你的精确信息都会很有用:)
猜你喜欢
  • 2013-08-10
  • 1970-01-01
  • 2020-07-06
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多