Pri*_*ome 23 routes internationalization reactjs next.js
我正在使用Next.js i18n-routing来设置多语言网站。这非常有效。如果我在此创建一个文件,/pages/about.js将根据我的区域设置创建 URL,例如:
/about/de/about/es/about那就好了。
如果我想要每种语言的翻译 URL 路由怎么办?我被困在如何设置这个问题上......
/about/de/uber-uns/es/nosotros?
jul*_*ves 31
您可以通过rewrites在文件中利用来实现翻译后的 URL 路由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
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
此外,如果您希望在客户端导航期间保持一致的路由行为,您可以在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
Run Code Online (Sandbox Code Playgroud)
然后在您的代码中使用TranslatedLink而不是。next/link
<TranslatedLink href='/about'>
<a>Go to About page</a>
</TranslatedLink>
Run Code Online (Sandbox Code Playgroud)
请注意,您可以重用该pathTranslations对象来动态生成rewrites数组,next.config.js并为翻译后的 URL 提供单一的真实来源。
| 归档时间: |
|
| 查看次数: |
15754 次 |
| 最近记录: |