Improve I18n.translate to enable nested ui.json

This commit is contained in:
Robbie Antenesse 2019-12-01 13:33:20 -07:00
parent 1458e936ea
commit 3c40673774
1 changed files with 31 additions and 17 deletions

View File

@ -29,31 +29,45 @@ export class I18n {
}); });
} }
translate (section, phrase) { translate (target, useDefault = false) {
let result; let language = useDefault ? this.default : this.language;
let language = this.default; const pieces = target.split('.');
if (!this.needsFetch && this.appState.language !== this.language.locale) { if (!this.needsFetch && !useDefault && this.appState.language !== language.locale) {
console.warn(`The target language (${this.appState.language}) does not exist. Defaulting to ${this.default.name} (${this.default.locale}).`); console.warn(`The target language (${this.appState.language}) does not exist. Defaulting to ${this.default.name} (${this.default.locale}).`);
} else if (typeof this.language[section] == 'undefined' || typeof this.language[section][phrase] == 'undefined') { language = this.default;
console.warn(`The translation for "${section}.${phrase}" is not set in the ${this.language.locale} locale. Using ${this.default.name} (${this.default.locale}) instead.`);
} else {
language = this.language;
} }
if (typeof language[section] !== 'undefined' && typeof language[section][phrase] !== 'undefined') { let translation = pieces.reduce((lang, piece, i) => {
result = language[section][phrase]; if (lang === false) return false;
} else {
console.error(`The translation for "${section}.${phrase}" is set up in neither the target nor default locale.`); if (typeof lang[piece] === 'object') {
result = `${section}.${phrase}`; // Only continue if there's another piece, otherwise, it will error.
if (typeof pieces[i + 1] !== 'undefined') {
return lang[piece];
}
} }
return result; if (typeof lang[piece] === 'string') {
return lang[piece];
}
return false;
}, Object.assign({}, language));
if (translation === false) {
if (language.locale !== this.default.locale) {
console.warn(`The translation for "${target}" is not set in the ${this.language.locale} locale. Using ${this.default.name} (${this.default.locale}) instead.`);
return this.translate(target, true);
}
console.error(`The translation for "${target}" is set up in neither the target nor default locale.`);
return target;
}
return translation;
} }
__ (translation) { __ (translation) {
const pieces = translation.split('.'); return this.translate(translation);
const result = this.translate(pieces[0], pieces[1]);
return result;
} }
} }