如何在 Next.js 中设置 i18n 翻译的 URL 路由? [英] How to setup i18n translated URL routes in Next.js?
问题描述
我正在使用 Next.js i18n-routing 来设置多语言网站.这完美地工作.如果我在 /pages/about.js
中创建一个文件,这将根据我的区域设置创建 URL,例如:
I am using Next.js i18n-routing to setup multi-language website. This works perfectly. If I create a file in /pages/about.js
this will create URLs based on my locale settings, for example:
- EN ->
/about
- DE ->
/de/about
- ES ->
/it/about
没关系.
如果我想为每种语言翻译 URL 路由怎么办?我被困在如何设置它...
What if I want to have a translated URL routes for each language? I am stuck on how to set this up...
- EN ->
/about
- DE ->
/de/uber-uns
- ES ->
/it/nosotros
?
推荐答案
您可以通过利用 rewrites
在您的 next.config.js
文件中.
You can achieve translated URL routes by leveraging rewrites
in your next.config.js
file.
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.
Furthermore, if you want a consistent routing behaviour during client-side navigations, you can create a wrapper around the next/link
component to ensure the translated URLs are displayed.
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
.
Then use TranslatedLink
instead of next/link
in your code.
<TranslatedLink href='/about'>
<a>Go to About page</a>
</TranslatedLink>
请注意,您可以重用 pathTranslations
对象来动态生成 next.config.js
中的 rewrites
数组并具有单一源翻译网址的真实性.
Note that you could reuse the pathTranslations
object to dynamically generate the rewrites
array in the next.config.js
and have a single source of truth for the translated URLs.
这篇关于如何在 Next.js 中设置 i18n 翻译的 URL 路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!