From 0bc0a6bc8ccecd4fb453b1799c3c7148770cecad Mon Sep 17 00:00:00 2001 From: long_long_float Date: Fri, 16 Dec 2016 20:31:03 +0900 Subject: [PATCH] :star: new: locale checking (#98) by @long-long-float * add $texist * add document for $texist --- gitbook/api.md | 12 ++++++++++++ src/extend.js | 24 ++++++++++++++++++++++++ test/specs/i18n.js | 20 ++++++++++++++++++++ 3 files changed, 56 insertions(+) diff --git a/gitbook/api.md b/gitbook/api.md index f151ca2de..e85315cec 100644 --- a/gitbook/api.md +++ b/gitbook/api.md @@ -167,3 +167,15 @@ - **Usage:** Translate the locale of `keypath` with pluralization. Translate in preferentially component locale than global locale. If not specified component locale, translate with global locale. If you will specify String value to `arguments`, translate the locale of value. If you wll specify Array or Object value to `arguments`, you must specify with `arguments` of [$t](#tkeypath-lang-arguments). + +### $texist(keypath, [arguments]) + +- **Arguments:** + - `{String} keypath` + - `{Array | Object} [arguments]` + +- **Return:** + Whether keypath exists (Boolean) + +- **Usage:** + Return whether key path exists in Boolean. diff --git a/src/extend.js b/src/extend.js index 2c4287ae0..0116f0f82 100644 --- a/src/extend.js +++ b/src/extend.js @@ -193,5 +193,29 @@ export default function (Vue) { return fetchChoice(this.$t(key, ...args), choice) } + /** + * $texist + * + * @param {String} key + * @param {Array} ...args + * @return {Boolean} + * + */ + + Vue.prototype.$texist = function (key, ...args) { + if (!key) { return false } + const { lang, fallback, params } = parseArgs(...args) + + let locale + if (this.$options.locales) { + locale = bind(getComponentLocale, this) + } else { + locale = getAssetLocale + } + + const result = translate(locale, lang, fallback, key, params) + return !isNil(result) + } + return Vue } diff --git a/test/specs/i18n.js b/test/specs/i18n.js index c8914a2bc..fe91ea5cc 100644 --- a/test/specs/i18n.js +++ b/test/specs/i18n.js @@ -487,6 +487,26 @@ describe('i18n', () => { }) }) + describe('$texist', () => { + describe('existing key', () => { + it('should return true', () => { + const vm = new Vue() + assert.equal(vm.$texist('message.hello'), true) + }) + + it('should return true with language', () => { + const vm = new Vue() + assert.equal(vm.$texist('message.hello', 'ja'), true) + }) + }) + + describe('not existing key', () => { + it('should return false', () => { + const vm = new Vue() + assert.equal(vm.$texist('message.hallo'), false) + }) + }) + }) describe('reactive translation', () => { let el