Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active October 24, 2021 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save james2doyle/d00e06a5f4963a539e3aa0b2d5283d11 to your computer and use it in GitHub Desktop.
Save james2doyle/d00e06a5f4963a539e3aa0b2d5283d11 to your computer and use it in GitHub Desktop.
An incredibly simple i18n translation function using lodash `get` and `template` functions
/**
* An incredibly simple i18n translation function using lodash `get` and `template` functions
*
* if `key.hello-message` was "Hello {msg}!"
*
* intl('key.hello-message', { msg: 'world' }) // "Hello world!"
*/
import { get, template, memoize } from 'lodash';
// @ references root project dir
const en = require('@/lang/en.json');
/**
* Translate a string from a preloaded JSON document
*/
function intl(key: string, values: Record<string, string | number> = {}): string {
const compiled = template(get(en, key), {
interpolate: /{([\s\S]+?)}/g, // {myVar}
});
return compiled(values);
};
export default memoize(intl);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment