Created
February 10, 2019 14:58
-
-
Save jancassio/c43a8aa57109b6be95c2acbe2cf7fc55 to your computer and use it in GitHub Desktop.
Dead simple JavaScript i18n implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// dead stupid simple i18n implementation | |
/** | |
* i18n function allows to pick a string from a json (could be yml as well) and render it based on language. | |
* | |
* Examples: | |
* ``` | |
* const enUS = i18n('en-us'); // load a function that provides all en-us strings. | |
* const ptBR = i18n('pt-br'); // load a function that provides all pt-br strings. | |
* | |
* const title = enUS('hello world'); // assign the value of 'hello world' entry from the './strings.en-us.json'. | |
* const title = enUS('hello world'); // assign the value of 'hello world' entry from the './strings.pt-br.json'. | |
*/ | |
module.exports = (lang, baseArgs = {}) => (key, args = {}) => { | |
const texts = require(`./strings.${lang}.json`); | |
let template = texts[key]; | |
args = Object.assign({}, baseArgs, args); | |
return (key, args = {}) => { | |
if (args) { | |
Object.keys(args).forEach(key => { | |
const rgxp = new RegExp(`{{${key}}}`, 'gi'); | |
template = template.replace(rgxp, args[key]); | |
}); | |
} | |
return template; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment