roddeh / i18njs

Internationalisation library for JS projects
MIT License
64 stars 17 forks source link

What about object notation? #18

Open xreider opened 3 years ago

xreider commented 3 years ago

locale:

  navbar: {
    menu: {
      listOfTutorials: 'List of tutorials',
    },
  },

I want to display t('navbar.menu.listOfTutorials')

but nothing happens

roddeh commented 3 years ago

The format of the translations objects is already somewhat complex to allow for the various use cases e.g. pluralisation, contexts etc. Rather than introduce further complexity it can perhaps be handled by an external transformation function for example...

const keys = {
    navbar:{
        menu:{
            listOfTutorials: 'List of tutorials',
        },
        topLevelItem: 'Top Level Menu Item'
    },
    title:'My Title'
}

const flattenKeys = ({keys, prefix}) => {
    let result = {};
    for(key in keys){
        const type = typeof keys[key];
        if(type === 'string'){
            result[`${prefix}${key}`] = keys[key];
        }
        else if(type === 'object'){
            result = {...result, ...flattenKeys({keys:keys[key], prefix: `${prefix}${key}.`})}
        }
    }
    return result
}
const flattened = flattenKeys({keys, prefix:''})
i18n.translator.add({values:flattened});

console.log(i18n('navbar.menu.listOfTutorials')) // => 'List of tutorials'
console.log(i18n('title')) // => 'My Title'