Reputation: 346
Is there a way in nuxt.js middleware to know the language used for the request (of the page)?
By taking the example proposed by nuxt.js (https://nuxtjs.org/api/pages-middleware/) and by supposing that for example a page declined in two languages (French and English) with the following urls:
When visiting the first or second url, can we have an indicator on the language used directly in the middleware? Or should you parse the page url to find out (route)?
Because I want to redirect the user according to the language requested...
Upvotes: 3
Views: 4032
Reputation: 1424
If you're using nuxt-i18n
module, is really simple, and you have two ways of doing it. I'll suggest the first, but I think it would be cool to give a perspective on how the module works.
Both of the solutions have the same starting point, getting the i18n
from the middleware context
. i18n
should be accessed from the app
parameters from the context
, so we start from here:
export default async function({ app: { i18n } }) {}
i18n
module do the hard liftingThe same way you can access the translations inside Vue components using the $t
method, we could use it from the i18n
object directly.
So if you would write in a Vue Component
$t('components.login.register')
Then in the middleware you would do
i18n.t('components.login.register')
i18n
module betterIf you inspect the i18n
object that the module exposes, you can find the following parameters is contains:
locale
- That represents the current languagemessages
- An object that keeps the translations for each active languageso you could easily get the previous example translation like this:
const { messages, locale } = i18n
const currentTranslations = messages[locale]
const wantedTranslation = currentTranslations.components.login.register
I'd suggest for you to use the i18n.t
module, as it works some of the abstractions you'd need to rewrite yourself, but it's a good example to understand the module better.
Upvotes: 3