Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow default value in nested translation #2174

Closed
bschoenmaeckers opened this issue Apr 14, 2024 · 3 comments
Closed

Allow default value in nested translation #2174

bschoenmaeckers opened this issue Apr 14, 2024 · 3 comments

Comments

@bschoenmaeckers
Copy link

馃殌 Feature Proposal

Currently I don't think its possible to provide a default value for when a nested translations cannot be found.

Motivation

When templating nested translations, its posible that the nested key is not present, so it would lead to a broken translation.

Example

Given the following translation file:

{
  "message": "Something went wrong: $t(error_code.{{error_type}}, {\"defaultValue\": \"Unknown error\"})"
  "error_type": {
    "it_error": "it went wrong"
  }
}

t('message', {error_type: 'other_error'}) will translate to "Something went wrong: error_code.other_error" but I would like it to translate to "Something went wrong: Unknown error".

@adrai
Copy link
Member

adrai commented Apr 14, 2024

There are 2 options:

Option 1: Use multiple fallback keys like described here: https://www.i18next.com/translation-function/essentials#multiple-fallback-keys

import i18next from 'i18next';

i18next.init({
    fallbackLng: 'en',
    resources: {
        en: {
            translation: {
                message: "Something went wrong:",
                error: {
                    "unspecific": "$t(message) Unknown error",
                    "it_error": "$t(message) it went wrong"
                }
            }
        }
    }
})

const existingError = 'it_error'
const nonExistingError = 'other_error'

console.log(i18next.t([`error.${existingError}`, 'error.unspecific']))
console.log(i18next.t([`error.${nonExistingError}`, 'error.unspecific']))

Option 2: Update i18next to v23.11.2 ;-)

@adrai adrai closed this as completed Apr 14, 2024
@bschoenmaeckers
Copy link
Author

Wow that was quick. Tnx!

@adrai
Copy link
Member

adrai commented Apr 14, 2024

If you like this module don鈥檛 forget to star this repo. Make a tweet, share the word or have a look at our https://locize.com to support the devs of this project.

There are many ways to help this project 馃檹

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants