Skip to content

Instantly share code, notes, and snippets.

@pieterbeulque
Created October 26, 2015 14:39
Show Gist options
  • Save pieterbeulque/2abb560b28b46e946632 to your computer and use it in GitHub Desktop.
Save pieterbeulque/2abb560b28b46e946632 to your computer and use it in GitHub Desktop.
// app.translate('foo.bar') renders this.translations.foo.bar
// app.translate('foo.bar', 'baz') renders this.translations.foo.bar, replacing any ${} syntax with 'baz'
// app.translate('foo.bar', { hello: 'world' }) renders this.translations.foo.bar, replacing ${hello} with 'world'
translate (key, replace) {
if (!this.translations) {
return '';
}
let translation = this.translations;
key = key.split('.');
for (let k of key) {
k = k.replace(/([a-z])([A-Z])/g, (match, before, after) => {
return `${before}_${after.toLowerCase()}`
}).toLowerCase();
try {
translation = translation[k];
if (translation === undefined) {
return '';
}
} catch (e) {
return '';
}
}
if (!!replace) {
if (typeof replace === 'object') {
for (let key in replace) {
let value = replace[key];
translation = translation.replace('${' + key + '}', value);
}
} else {
translation = translation.replace(/\$\{[\w\d]+\}/gi, replace);
}
}
return translation;
}
@fd
Copy link

fd commented Oct 26, 2015

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment