Home > database >  i18next return translation of all languages as object
i18next return translation of all languages as object

Time:09-28

In my Express app, I want to return error descriptions in all supported languages of my frontend app. Payload should be ideally something like: { errors: [messages: { de: “Passwort zu kurz”, en: “Password too short”}]}

As I don’t want to put the language dependent text directly in my route coding, I thought about using i18n-next. However, I don’t want to get one language back using the t(key) function but all of the languages of the respective language jsons for a specific key.

So ideally I would get something like: { errors: [message: functionINeed(“password_short”)]}

I would then have two language files for de and en from which the text is drawn from.

Does anyone know how to achieve this?

CodePudding user response:

I don't think there is such functionality exposed as part of i18next's public API. However, you can still achieve your end goal with the following function:

function getTranslationsForKey(key) {
  return i18next.languages.reduce((messages, currentLang) => {
    messages[currentLang] = i18next.t(key, { lng: currentLang });
    return messages
  }, {});
}

const errors = getTranslationsForKey('password_short');

console.log(errors);

// output:
{
     en: 'Password too short',
     de: 'Passwort zu kurz'
}

It iterates over every configured i18next language, translates the provided key for the current language and builds a hash-map with all possible translations for the key.

  • Related