Search code examples
javascriptinternationalizationi18nextreact-i18next

i18next - dynamically add gender when context is used


I have the following:

t('translations::How are you?', { context: this.props.me.gender })

I'm currently using i18next-scanner to auto generate a JSON namespace file. The problem I am having is when I use context, I get:

"How are you?": "How are you?"     // fallback
"How are you?_": "How are you?"    // context

What I'd really like to happen is whenever context is used in i18n, I'd like male and female to be generated like so:

"How are you?": "How are you?"
"How are you?_male": "How are you?"
"How are you?_female": "How are you?"

I haven't found a good way to dynamically add these keys. What things can I try?


Solution

  • I'v reviewed the libs source code, from the tests, it looks like this lib is not supports this.

    But, from this code, if your options.context is a function, it will be invoked, that means that you will able to modify it. Check this code: https://codesandbox.io/s/laughing-ptolemy-vd1xb

    As you can see, I've managed to change the context type, but the lib is not supporting your case (base on this line) it adds only one context.

    It can be a really simple PR :]

    Edit I've added this functionality to i18next-scanner, now you can specify contextDefaultValues- a list of values that will be used in a case of dynamic context values.

    // i18next-scanner.config.js
    
    module.exports = {
        input: [
            'app/**/*.{js,jsx}',
            // Use ! to filter out files or directories
            '!app/**/*.spec.{js,jsx}',
            '!app/i18n/**',
            '!**/node_modules/**',
        ],
        output: './',
        options: {
            ...
            contextDefaultValues: ['male', 'female'] // <--- specify this option  
            ...
        },
        ...
    };