From 1b257c3c4c8aa2aeacef1b502dc0f4892e5b514c Mon Sep 17 00:00:00 2001 From: Artur Arseniev Date: Thu, 31 Oct 2019 09:01:38 +0100 Subject: [PATCH] Add custom locale and interpolation --- src/i18n/index.js | 25 +++++++++++++++++-------- test/specs/i18n/index.js | 25 +++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 8 deletions(-) diff --git a/src/i18n/index.js b/src/i18n/index.js index 64085c47c..9e87ff02d 100644 --- a/src/i18n/index.js +++ b/src/i18n/index.js @@ -142,24 +142,33 @@ export default () => { /** * Translate the locale message * @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} * @example * obj.setMessages({ * en: { msg: 'Msg', msg2: 'Msg {test}'}, - * it: { msg: 'Msg it'}, + * it: { msg2: 'Msg {test} it'}, * }); * obj.t('msg'); * // -> outputs `Msg` - * obj.t('msg', { l: 'it' }); // change locale - * // -> outputs `Msg it` - * obj.t('msg2', { test: 'hello' }); // pass params + * obj.t('msg2', { test: 'hello' }); // use params * // -> outputs `Msg hello` + * obj.t('msg2', { test: 'hello' }, { l: 'it' }); // custom local + * // -> outputs `Msg hello it` */ - t(key, params = {}) { - const locale = params.l || this.getLocale(); + t(key, params, opts = {}) { + const param = params || {}; + const locale = opts.l || this.getLocale(); 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; } }; }; diff --git a/test/specs/i18n/index.js b/test/specs/i18n/index.js index 34757d7b5..baab1baca 100644 --- a/test/specs/i18n/index.js +++ b/test/specs/i18n/index.js @@ -67,5 +67,30 @@ describe('I18n', () => { expect(obj.t('msg2')).toBe(undefined); 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' + ); + }); }); });