Browse Source

Add custom locale and interpolation

pull/2385/head
Artur Arseniev 7 years ago
parent
commit
1b257c3c4c
  1. 25
      src/i18n/index.js
  2. 25
      test/specs/i18n/index.js

25
src/i18n/index.js

@ -142,24 +142,33 @@ export default () => {
/** /**
* Translate the locale message * Translate the locale message
* @param {String} key Label to translate * @param {String} key Label to translate
* @param {Object} params Params for the translation * @param {Object} [params] Params for the translation
* @param {Object} [opts] Options for the translation
* @returns {String} * @returns {String}
* @example * @example
* obj.setMessages({ * obj.setMessages({
* en: { msg: 'Msg', msg2: 'Msg {test}'}, * en: { msg: 'Msg', msg2: 'Msg {test}'},
* it: { msg: 'Msg it'}, * it: { msg2: 'Msg {test} it'},
* }); * });
* obj.t('msg'); * obj.t('msg');
* // -> outputs `Msg` * // -> outputs `Msg`
* obj.t('msg', { l: 'it' }); // change locale * obj.t('msg2', { test: 'hello' }); // use params
* // -> outputs `Msg it`
* obj.t('msg2', { test: 'hello' }); // pass params
* // -> outputs `Msg hello` * // -> outputs `Msg hello`
* obj.t('msg2', { test: 'hello' }, { l: 'it' }); // custom local
* // -> outputs `Msg hello it`
*/ */
t(key, params = {}) { t(key, params, opts = {}) {
const locale = params.l || this.getLocale(); const param = params || {};
const locale = opts.l || this.getLocale();
const msgSet = this.getMessages(locale) || {}; const msgSet = this.getMessages(locale) || {};
return msgSet[key]; const reg = new RegExp(`\{([\\w\\d-]*)\}`, 'g');
let result = msgSet[key];
result = result
? result.replace(reg, (m, val) => param[val] || '').trim()
: result;
return result;
} }
}; };
}; };

25
test/specs/i18n/index.js

@ -67,5 +67,30 @@ describe('I18n', () => {
expect(obj.t('msg2')).toBe(undefined); expect(obj.t('msg2')).toBe(undefined);
expect(obj.t('msg1')).toBe(msg1); expect(obj.t('msg1')).toBe(msg1);
}); });
test('Translate method with custom locale', () => {
const msg1 = 'Msg 1';
const msg1Alt = `${msg1} it`;
obj.setLocale('en');
obj.setMessages({
en: { msg1 },
it: { msg1: msg1Alt }
});
expect(obj.t('msg1', null, { l: 'it' })).toBe(msg1Alt);
});
test('Translate method with a param', () => {
const msg1 = 'Msg 1 {test}';
const msg1Alt = `${msg1} it`;
obj.setLocale('en');
obj.setMessages({
en: { msg1 },
it: { msg1: msg1Alt }
});
expect(obj.t('msg1', { test: 'Hello' })).toBe('Msg 1 Hello');
expect(obj.t('msg1', { test: 'Hello' }, { l: 'it' })).toBe(
'Msg 1 Hello it'
);
});
}); });
}); });

Loading…
Cancel
Save