mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-14 18:13:54 +00:00
159021eabe
Today I was implementing an i18n according to this example in one of my projects. Unfortunately, current example fails if (for example) our `defaultLocale` is `en` and our url is `example.com/en/` or `example.com/en/news`: middleware redirects into `example.com//` and `example.con//news` respectively. I've fixed the example (not sure if it is the most elegant way to do it though), so it replaces `/en/` with `/`.
22 lines
885 B
JavaScript
22 lines
885 B
JavaScript
export default function ({ isHMR, app, store, route, params, error, redirect }) {
|
|
const defaultLocale = app.i18n.fallbackLocale
|
|
// If middleware is called from hot module replacement, ignore it
|
|
if (isHMR) return
|
|
// Get locale from params
|
|
const locale = params.lang || defaultLocale
|
|
if (store.state.locales.indexOf(locale) === -1) {
|
|
return error({ message: 'This page could not be found.', statusCode: 404 })
|
|
}
|
|
// Set locale
|
|
store.commit('SET_LANG', locale)
|
|
app.i18n.locale = store.state.locale
|
|
// If route is /<defaultLocale>/... -> redirect to /...
|
|
if (locale === defaultLocale && route.fullPath.indexOf('/' + defaultLocale) === 0) {
|
|
const toReplace = '^/' + defaultLocale + (route.fullPath.indexOf('/' + defaultLocale + '/') === 0 ? '/' : '')
|
|
const re = new RegExp(toReplace)
|
|
return redirect(
|
|
route.fullPath.replace(re, '/')
|
|
)
|
|
}
|
|
}
|