Skip to content

Instantly share code, notes, and snippets.

@jancassio
Created February 10, 2019 14:58
Show Gist options
  • Save jancassio/c43a8aa57109b6be95c2acbe2cf7fc55 to your computer and use it in GitHub Desktop.
Save jancassio/c43a8aa57109b6be95c2acbe2cf7fc55 to your computer and use it in GitHub Desktop.
Dead simple JavaScript i18n implementation
// 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