代码之家  ›  专栏  ›  技术社区  ›  Primoz Rome

如何在Next.js中设置i18n翻译的URL路由?

  •  0
  • Primoz Rome  · 技术社区  · 4 年前

    我正在使用 Next.js i18n-routing /pages/about.js 这将根据我的区域设置创建URL,例如:

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

    如果我想为每种语言提供翻译后的URL路由,该怎么办?我被困在如何设置这个。。。

    • EN-> /关于
    • 德-> /de/uber-uns
    • /it/nosotros

    ?

    0 回复  |  直到 4 年前
        1
  •  1
  •   juliomalves    4 年前

    您可以通过利用 rewrites next.config.js

    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 而不是

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

    请注意,您可以重用 pathTranslations 对象来动态生成 数组中的 next.config.js