From 363d157f30aa6932f89b8b7e9fe178d3afc868cb Mon Sep 17 00:00:00 2001 From: Artur Arseniev Date: Sat, 2 Nov 2019 20:22:42 +0100 Subject: [PATCH] Make localeFallback work --- src/i18n/index.js | 28 ++++++++++++++++++++-------- test/specs/i18n/index.js | 10 ++++++++++ 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/src/i18n/index.js b/src/i18n/index.js index 7a2624e22..5434a8c64 100644 --- a/src/i18n/index.js +++ b/src/i18n/index.js @@ -181,15 +181,33 @@ export default () => { * // -> outputs `Msg hello it` */ t(key, opts = {}) { - const { em } = this; + const { config } = this; const param = opts.params || {}; const locale = opts.l || this.getLocale(); + const localeFlb = opts.lFlb || config.localeFallback; + let result = this._getMsg(key, locale, opts); + + // Try with fallback + if (!result) result = this._getMsg(key, localeFlb, opts); + + !result && + this._warn(`'${key}' i18n key not found in '${locale}' lang`, opts); + result = result ? this._addParams(result, param) : result; + + return result; + }, + + _addParams(str, params) { + const reg = new RegExp(`\{([\\w\\d-]*)\}`, 'g'); + return str.replace(reg, (m, val) => params[val] || '').trim(); + }, + + _getMsg(key, locale, opts = {}) { const msgSet = this.getMessages(locale, opts); // Lang set is missing if (!msgSet) return; - const reg = new RegExp(`\{([\\w\\d-]*)\}`, 'g'); let result = msgSet[key]; // Check for nested getter @@ -200,12 +218,6 @@ export default () => { }, msgSet); } - !result && - this._warn(`'${key}' i18n key not found in '${locale}' lang`, opts); - result = result - ? result.replace(reg, (m, val) => param[val] || '').trim() - : result; - return result; }, diff --git a/test/specs/i18n/index.js b/test/specs/i18n/index.js index d1bb8653f..a309dac6e 100644 --- a/test/specs/i18n/index.js +++ b/test/specs/i18n/index.js @@ -118,6 +118,16 @@ describe('I18n', () => { expect(obj.t('msg1', { l: 'it' })).toBe(msg1Alt); }); + test('Translate method with fallback locale', () => { + const msg1 = 'Msg en'; + obj.setLocale('it'); + obj.setMessages({ + en: { msg1 }, + it: {} + }); + expect(obj.t('msg1')).toBe(msg1); + }); + test('Translate method with a param', () => { const msg1 = 'Msg 1 {test}'; const msg1Alt = `${msg1} it`;