【问题标题】:How to setup i18n translated URL routes in Next.js?如何在 Next.js 中设置 i18n 翻译的 URL 路由?
【发布时间】:2021-10-13 19:43:01
【问题描述】:

我正在使用Next.js i18n-routing 设置多语言网站。这完美地工作。如果我在 /pages/about.js 中创建一个文件,这将根据我的区域设置创建 URL,例如:

  • EN -> /about
  • 德->/de/about
  • ES -> /it/about

没关系。

如果我想为每种语言提供翻译的 URL 路由怎么办?我被困在如何设置它...

  • EN -> /about
  • 德->/de/uber-uns
  • ES -> /it/nosotros

?

【问题讨论】:

  • 好问题。如果您已经找到处理路线翻译的更好方法,请告诉我们。

标签: reactjs routes internationalization next.js


【解决方案1】:

您可以通过在您的 next.config.js 文件中利用 rewrites 来实现已翻译的 URL 路由。

module.exports = {
    i18n: {
        locales: ['en', 'de', 'es'],
        defaultLocale: 'en'
    },
    async rewrites() {
        return [
            {
                source: '/de/uber-uns',
                destination: '/de/about',
                locale: false // Use `locale: false` so that the prefix matches the desired locale correctly
            },
            {
                source: '/es/nosotros',
                destination: '/es/about',
                locale: false
            }
        ]
    }
}

此外,如果您希望在客户端导航期间保持一致的路由行为,您可以围绕 next/link 组件创建一个包装器,以确保显示翻译后的 URL。

import { useRouter } from 'next/router'
import Link from 'next/link'

const pathTranslations = {
    de: {
        '/about': '/uber-uns'
    },
    es: {
        '/about': '/sobrenos'
    }
}

const TranslatedLink = ({ href, children }) => {
    const { locale } = useRouter()
    // Get translated route for non-default locales
    const translatedPath = pathTranslations[locale]?.[href] 
    // Set `as` prop to change displayed URL in browser
    const as = translatedPath ? `/${locale}${translatedPath}` : undefined

    return (
        <Link href={href} as={as}> 
            {children}
        </Link>
    )
}

export default TranslatedLink

然后在您的代码中使用TranslatedLink 而不是next/link

<TranslatedLink href='/about'>
    <a>Go to About page</a>
</TranslatedLink>

请注意,您可以重用 pathTranslations 对象在 next.config.js 中动态生成 rewrites 数组,并为翻译后的 URL 提供单一真实来源。

【讨论】:

  • 我正在研究重写,但这似乎有点笨拙来管理 9 种语言和 100 页的重写。此外,您还有动态路线,这会使重写变得越来越复杂。
  • 绝对是 - 这是一个简单的解决方案,无法很好地扩展。您可能需要考虑添加 custom server 以获得更复杂和可扩展的解决方案。
猜你喜欢
  • 2021-07-08
  • 2013-12-26
  • 1970-01-01
  • 2020-10-23
  • 1970-01-01
  • 1970-01-01
  • 2019-11-18
  • 2012-02-22
  • 2010-09-22
相关资源
最近更新 更多