Merc
Merc

Reputation: 4570

nuxt3 i18n: how can I localize dynamic slugs

I am struggling with localizing slugs for a nuxt3 app with i18n (https://i18n.nuxtjs.org/docs/getting-started).

I want to define some localized slugs somewhere. I tried for example to set them in my nuxt config:

i18n: {
    strategy: 'prefix_except_default',
    detectBrowserLanguage: false,
    defaultLocale: 'de',
    baseUrl: process.env.NUXT_PUBLIC_SITE_URL,
    locales: [
      {
        name: 'Deutsch',
        code: 'de',
        language: 'de-CH',
      },
      {
        name: 'English',
        code: 'en',
        language: 'en-US',
      },
    ],
    customRoutes: 'config',
    pages: {
      yesterday: {
        en: '/yesterday',
        de: '/gestern',
      },
      dataprivacy: {
        en: '/dataprivacy',
        de: '/datenschutz',
      },
      imprint: {
        en: '/imprint',
        de: '/impressum',
      },
    },
  },

I then create a /pages/slug.vue file.

And because I have a lang switcher I want to be able to retrieve localized paths for 'imprint' and 'dataprivacy'.

I tried things like

<script setup>
const localePath = useLocalePath()
const localeRoute = useLocaleRoute()

console.log(localePath('dataprivacy', 'de')) // Outputs: "/datenschutz"
console.log(localePath('dataprivacy', 'en')) // Outputs: "/dataprivacy"

console.log('route 1: ', localeRoute('/en/dataprivacy', 'de'))
// outputs:
// route 1: Object { fullPath: "/dataprivacy", hash: "", query: {}, name: "slug___de", path: "/dataprivacy", params: {…}, matched: (1) […], meta: {}, redirectedFrom: undefined, href: "/dataprivacy" }

console.log('route 2: ', localeRoute('/dataprivacy', 'de'))
// outputs:
// route 2: Object { fullPath: "/dataprivacy", hash: "", query: {}, name: "slug___de", path: "/dataprivacy", params: {…}, matched: (1) […], meta: {}, redirectedFrom: undefined, href: "/dataprivacy" }

console.log('route 3: ', localeRoute('dataprivacy', 'de'))
// outputs:
// route3: undefined

For the 'yesterday' it works because I have a template called yesterday.vue but with the dynamic slug I can't get it to work.

But how can I have a function where I can put 'imprint' as a parameter and the locale as a second and get the localized route?

Example:

myDummyRouteFunction('imprint', 'de') // -> '/impressum'
myDummyRouteFunction('imprint', 'en') // -> '/en/imprint'

I can not really make any sense of the docs; https://i18n.nuxtjs.org/docs/guide/custom-paths#dynamic-route-parameters

👋

===== Edit:

I created a repo for reproduction: https://github.com/Jones-S/nuxt-i18n-demo

Also I realized that v9 seems to be buggy. While the langswitch for the defined pages works, the messages don't! If I downgrade to v8, they both work. My initial question remains though.

Upvotes: 0

Views: 36

Answers (0)

Related Questions