From 9cab1e1e9ed417a8ac508dc6e56b8a1aa02f9114 Mon Sep 17 00:00:00 2001 From: Artur Arseniev Date: Thu, 31 Oct 2019 08:30:57 +0100 Subject: [PATCH] Add translate method to i18n --- src/i18n/index.js | 23 +++++++++++++++++++++++ test/specs/i18n/index.js | 11 +++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/i18n/index.js b/src/i18n/index.js index bc57b1c0b..64085c47c 100644 --- a/src/i18n/index.js +++ b/src/i18n/index.js @@ -137,6 +137,29 @@ export default () => { } }); return this; + }, + + /** + * Translate the locale message + * @param {String} key Label to translate + * @param {Object} params Params for the translation + * @returns {String} + * @example + * obj.setMessages({ + * en: { msg: 'Msg', msg2: 'Msg {test}'}, + * it: { msg: 'Msg it'}, + * }); + * obj.t('msg'); + * // -> outputs `Msg` + * obj.t('msg', { l: 'it' }); // change locale + * // -> outputs `Msg it` + * obj.t('msg2', { test: 'hello' }); // pass params + * // -> outputs `Msg hello` + */ + t(key, params = {}) { + const locale = params.l || this.getLocale(); + const msgSet = this.getMessages(locale) || {}; + return msgSet[key]; } }; }; diff --git a/test/specs/i18n/index.js b/test/specs/i18n/index.js index 730b9e441..34757d7b5 100644 --- a/test/specs/i18n/index.js +++ b/test/specs/i18n/index.js @@ -56,5 +56,16 @@ describe('I18n', () => { it: { msg1: 'Msg 1' } }); }); + + test('Translate method with global locale', () => { + const msg1 = 'Msg 1'; + obj.setLocale('en'); + obj.setMessages({ + en: { msg1 }, + it: { msg1: `${msg1} it` } + }); + expect(obj.t('msg2')).toBe(undefined); + expect(obj.t('msg1')).toBe(msg1); + }); }); });