javascriptnuxt.jsnuxt-i18n

How to create dynamic links in nuxt for each available language?


For my project I'm using Nuxt with i18n. In the .env file I've created an array with all available languages. Now in nuxt.config I'd like to configure the about menu for each available language. The about should be an object, holding the locale and the menu name, so i.e.:

about: {
  "nl-NL": process.env.ABOUT_NAME[0],
  en: process.env.ABOUT_NAME[1]
}

I don't want the available languages be hardcoded, they should be dynamic. So for each language in AVAILABLE_LOCALE.split(",") add property to the about object.

How can I achieve this? Right now I have this code:

nuxt.config.js

publicRuntimeConfig: {
  ABOUT: Array.from(process.env.ABOUT_NAME).forEach(lang => {
    this.language = lang;
  }),
}

.env

AVAILABLE_LOCALE='nl-NL,en,es'
ABOUT_NAME='Over ons,About us,Sobre nosotros'

Solution

  • Fixed it! This is the result that works for me:

        PAGE: {
          NAME: JSON.parse(
            JSON.stringify(
              process.env.PAGE_NAME.split(",")
                .map(function(translation) {
                  const index = process.env.PAGE_NAME.split(",").indexOf(
                    translation
                  );
                  let newObject = {};
                  newObject.id = index;
                  newObject.language = process.env.AVAILABLE_LOCALE.split(",")[
                    index
                  ];
                  newObject.name = translation;
                  return newObject;
                })
                .reduce((acc, obj) => {
                  let { name, language } = obj;
                  return { ...acc, [language.toUpperCase()]: name };
                }, {})
            )
          ),
          URL: JSON.parse(
            JSON.stringify(
              process.env.PAGE_NAME.split(",")
                .map(function(translation) {
                  const index = process.env.PAGE_NAME.split(",").indexOf(
                    translation
                  );
                  let newObject = {};
                  newObject.id = index;
                  newObject.language = process.env.AVAILABLE_LOCALE.split(",")[
                    index
                  ];
                  newObject.name = translation;
                  return newObject;
                })
                .reduce((acc, obj) => {
                  let { name, language } = obj;
                  return {
                    ...acc,
                    [language.toUpperCase()]: name
                      .replace(/\s+/g, "-")
                      .toLowerCase()
                  };
                }, {})
            )
          )
        },