Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do i18next have keyPrefix option?

I'm using i18next and react-18next for my project. When using useTranslation from react-i18next we have a nice option of "keyPrefix" to help us reducing code duplication. But sometimes I need to use i18next outside a component, so I wonder if it has any abstractions like useTranslation that can let me use ns or keyPrefix without repeating it everytime I use the t function?

I tried looking around i18next's documentations, but I can't find anything (yet?).

I tried to do it myself with adapter pattern, but the typescript support would break since I can't get the type of the key of t function.

like image 856
ngtrthinh Avatar asked Dec 28 '25 21:12

ngtrthinh


1 Answers

It is even easier to do so in i18next. I would just use react-i18next's documentation as an example:

// having JSON in namespace "translation" like this:
/*{
    "very": {
      "deeply": {
        "nested": {
          "key": "here"
        }
      }
    }
}*/
const { t } = useTranslation('translation', { keyPrefix: 'very.deeply.nested' });
const text = t('key'); // "here"

And in i18next (as mentioned in it's documentation):

// for different namespaces than default one
i18next.t('translation:very.deeply.nested.key');
// it is recommended to use the ns option:
i18next.t('very.deeply.nested.key', { ns: 'translation'});

And if you need to set it as default in some specific JavaScript files, check: i18next.getFixedT(lng, ns, keyPrefix).

Hope this answer helps

like image 70
hokwanhung Avatar answered Dec 31 '25 13:12

hokwanhung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!