NextJS i18next Nextjs本地化路由

问题描述 投票:0回答:1

我已经为我的NextJS网站完全实现了next-i18next。一切都按预期进行:

  • 使用i18next中间件自动检测语言
  • 使用语言选择按钮更改语言
  • 仅在相关名称空间中加载的翻译等

但是,我想本地化路线名称,以便它们反映所设置的语言。

我了解如何使用下一路线来完成此操作,这种交换特别有用:

How do I localize routes with next.js and next-i18next?

在该示例中,路线设置如下:

routes.add('en-home', '/', 'index')
routes.add('de-home', '/de', 'index')
routes.add('en-test', '/test', 'test')
routes.add('de-test', '/de/prufung', 'test')

我尝试使用以下模式作为示例,从下一条路由实现Route and Link:

  1. i18n.language获取当前语言
  2. 根据语言设置来设置链接URL
<Link route={`${lang}-home`}></Link>

同样,对下一路路由器使用类似的模式,例如:

Router.pushRoute(`${lang}-home`)

但是,这不起作用。

[我在引用的线程中注意到@ samuelg0rd0n评论说他创建了一个自定义Link组件。

[任何人都可以指导我如何根据网站设置的语言更改所有路线吗?

谢谢!

next.js i18next
1个回答
0
投票

我强烈建议您尝试使用Next.js官方示例:

Next.js-命名路由示例(下一个路由)

https://github.com/zeit/next.js/tree/canary/examples/with-next-routes

但是我看到它需要一个额外的服务器,并且如果我们将应用程序结构自定义为我自己的项目示例,也会失败:

| src/app
   | -- pages
       | -- post.js
       | -- category.js
   | -- server.js (for routes)

| src/functions
   | -- index.js (lambda function for server-side)

如果我运行next src/app,它将失败,并显示以下错误:

Error: > Couldn't find a `pages` directory. Please create one under the project root
    at findPagesDir (/home/paneladm/projects/paneladm-dev/travel-website/node_modules/next/dist/lib/find-pages-dir.js:3:170)
    at new DevServer (/home/paneladm/projects/paneladm-dev/travel-website/node_modules/next/dist/server/next-dev-server.js:1:3491)
    at createServer (/home/paneladm/projects/paneladm-dev/travel-website/node_modules/next/dist/server/next.js:2:105)
    at Object.<anonymous> (/home/paneladm/projects/paneladm-dev/travel-website/src/app/server.js:14:13)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)

Next.js团队现在正在使用一个简单的解决方案

此示例显示了如何通过利用Next.js内置的新自定义路由支持来消除使用下一路由的现有应用程序对自定义服务器的需求

您应将next更新为9.1.+,并按照以下方式实现自己的路由:

const nextRoutes = require('next-routes');
const routes = (module.exports = nextRoutes());

routes.add('category', '/category/:slug');
routes.add('post', '/post/:lang/:slug');

在您的next.config.js文件中,启用experimental属性并实现如下的rewrites方法:

const { routes } = require('./routes');

...

experimental: {
    rewrites() {
      const rewrites = [];

      for (const route of routes) {
        if (route.pattern !== route.page) {
          rewrites.push({
            source: route.pattern,
            destination: route.page,
          });
        }
      }

      return rewrites;
    }
  },

现在您的结构应该是:

| src/app
   | -- pages
       | -- post.js
       | -- category.js

但是,如果您要自定义页面,请尝试更改路由,如下所示:

...

routes.add('category/[slug]', '/category/:slug');
routes.add('post/[slug]', '/post/:lang/:slug');

它将指向pages --> category --> [slug].js文件。

在新的PR implementation文件中查看更多详细信息。

参考文献
© www.soinside.com 2019 - 2024. All rights reserved.