Browse Source

Make localeFallback work

pull/2385/head
Artur Arseniev 6 years ago
parent
commit
363d157f30
  1. 28
      src/i18n/index.js
  2. 10
      test/specs/i18n/index.js

28
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;
},

10
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`;

Loading…
Cancel
Save