From 446d76d9714434735feec86bb1529618c5f1c531 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Pluchino?= Date: Sun, 17 Jun 2018 10:03:29 +0200 Subject: [PATCH] Find locale in meta content language or html tag if it is not defined --- js/i18n-plugin.js | 38 +++++++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/js/i18n-plugin.js b/js/i18n-plugin.js index a6147c3..bade995 100644 --- a/js/i18n-plugin.js +++ b/js/i18n-plugin.js @@ -26,17 +26,35 @@ export default class BaseI18nPlugin extends BasePlugin * @returns {object} The language configuration */ locale(locale) { - if (!locale) { - locale = this.options.locale; + return this.constructor.locales[this.getLocale(locale)]; + } - if (!locale) { - if (undefined === globalLocale) { - let lang = document.querySelector('html').lang; - globalLocale = lang ? lang : null; - } + /** + * Get the valid available locale. + * + * @param {string} [locale] The ISO code of language + * + * @returns {object} The language configuration + */ + getLocale(locale) { + locale = locale ? locale : this.options.locale; + + if (this.constructor.locales[locale]) { + return locale; + } + + if (!locale) { + if (undefined === globalLocale) { + let metaLang = document.querySelector('head > meta[http-equiv="Content-Language"]'); + globalLocale = metaLang && metaLang.content ? metaLang.content : null; + } - locale = globalLocale; + if (undefined === globalLocale) { + let lang = document.querySelector('html').lang; + globalLocale = lang ? lang : null; } + + locale = globalLocale; } if (typeof locale === 'string') { @@ -52,7 +70,9 @@ export default class BaseI18nPlugin extends BasePlugin locale = localeKeys.length > 0 ? localeKeys[0] : 'en'; } - return this.constructor.locales[locale]; + this.options.locale = locale; + + return locale; } /**