Set up custom i18n implementation

This commit is contained in:
Robbie Antenesse 2019-09-09 16:19:39 -06:00
parent 58d1981a1f
commit 64bda6f982
2 changed files with 56 additions and 0 deletions

39
app/i18n/index.js Normal file
View File

@ -0,0 +1,39 @@
import en from './locales/en.json';
export class I18n {
constructor(appState) {
// Available languages should be kept up to date with the available locales.
this.availableLanguages = {
default: en,
en,
};
this.language = appState.language;
}
translate (section, phrase) {
let result;
let language = this.availableLanguages.default;
if (typeof this.availableLanguages[this.language] == 'undefined') {
console.warn(`The target language (${this.language}) does not exist. Defaulting to ${this.availableLanguages.default.name} (${this.availableLanguages.default.locale}).`);
} else if (typeof this.availableLanguages[this.language][section] == 'undefined' || typeof this.availableLanguages[this.language][section][phrase] == 'undefined') {
console.warn(`The translation for "${section}.${phrase}" is not set in the ${this.language} locale. Using ${this.availableLanguages.default.name} (${this.availableLanguages.default.locale}) instead.`);
} else {
language = this.availableLanguages[this.language];
}
if (typeof language[section] !== 'undefined' && typeof language[section][phrase] !== 'undefined') {
result = language[section][phrase];
} else {
console.error(`The translation for "${section}.${phrase}" is set up in neither the target nor default locale.`);
}
return result;
}
__ (translation) {
const pieces = translation.split('.');
const result = this.translate(pieces[0], pieces[1]);
return result;
}
}

17
app/i18n/locales/en.json Normal file
View File

@ -0,0 +1,17 @@
{
"name": "English",
"locale": "en",
"home": {
"subtitle": "An attempt at a viable alternative to Goodreads",
"temp_left": "Still gotta figure out a design.",
"temp_right": "It's early days, my friends!"
},
"login": {
"email": "Email",
"password": "Password",
"login_button": "Log In!"
},
"search": {
"header": "Search"
}
}