Skip to content

Instantly share code, notes, and snippets.

@daliborgogic
Last active October 14, 2024 22:38
Show Gist options
  • Save daliborgogic/1b3b7468d1afb8a67bcab7ca2091a705 to your computer and use it in GitHub Desktop.
Save daliborgogic/1b3b7468d1afb8a67bcab7ca2091a705 to your computer and use it in GitHub Desktop.
132 bytes i18n in Nuxt.js
export default defineNuxtRouteMiddleware(async (to) => {
const DEFAUT_LANGUAGE = 'en'
const supportedLanguages = ['sr'] // more provided soon
const allowedRouteNames = ['login', 'terms', 'privacy']
const { loggedIn, user } = useUserSession()
const { lang } = to.params
const isLang = supportedLanguages.includes(lang as string)
if (!loggedIn.value && !allowedRouteNames.includes(to.name as string)) {
return navigateTo('/login')
}
const isTestRoute = computed(() => (to.name as string).startsWith('lang-test'))
const isTestMode = computed(() => user.value.mode === 'test')
const testParam = computed(() => isTestMode.value ? 'test' : '')
if (to.name === 'lang' && isTestMode.value) {
return navigateTo({
name: isTestMode.value ? 'lang-test' : 'lang',
params: {
lang: isLang ? lang : ''
}
})
}
if (isTestRoute.value && testParam.value !== to.params.test) {
return navigateTo({
name: to.name,
params: { ...to.params, test: testParam.value, lang: isLang ? lang : '' }
})
}
try {
const filename = isLang ? lang : DEFAUT_LANGUAGE
const { default: locale } = await import(`./../i18n/${to.name}/${filename}.js`)
to.meta = { locale }
} catch (error) {
// ToDo: handle error
console.error(error)
}
})
@daliborgogic
Copy link
Author

daliborgogic commented Oct 9, 2024

Usage

export default defineNuxtRouteMiddleware(async (to) => {
  const { lang } = to.params
  const isLang = ['sr', 'de'].includes(lang)
  const filename = isLang ? lang : 'en'
  const { default: i18n } = await import(`./../i18n/${to.name}/${filename}.js`)
  // DE
  // {
  //  welcome: 'Willkommen!',
  //  hello: x => `Hallo ${x}!`,
  //  colors: [
  //    'Weiß',
  //    'Schwarz'
  //  ]
  // }
  to.meta = { t: useI18n(i18n) }
})
<script setup>
// No imports; Magic 🪄
</script>

<template>
{{ t('welcome') }}   <!-- Willkommen! -->
{{ t('hello', 'Dalibor') }}  <!-- Hallo Dalibor! -->
{{ t('colors.1') }}  <!-- Schwarz -->
</template>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment