From 08255e266b590e43c2c9362206928ff7c8a9ab5c Mon Sep 17 00:00:00 2001 From: Jo-Philipp Wich Date: Thu, 18 Oct 2018 09:52:07 +0200 Subject: luci-base: fix luci.i18n.setlanguage() Rework the setlanguage() implementation to actually switch catalogues if another language has been loaded previously and change it to return the effectively loaded language tag. Also improve input parameter validation and accept tags in both lower or upper case. Signed-off-by: Jo-Philipp Wich --- modules/luci-base/luasrc/i18n.lua | 28 ++++++++++++++++++++++------ modules/luci-base/luasrc/i18n.luadoc | 3 ++- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/modules/luci-base/luasrc/i18n.lua b/modules/luci-base/luasrc/i18n.lua index bcb16d5c0..968c387f1 100644 --- a/modules/luci-base/luasrc/i18n.lua +++ b/modules/luci-base/luasrc/i18n.lua @@ -23,15 +23,31 @@ function loadc(file, force) end function setlanguage(lang) - context.lang = lang:gsub("_", "-") - context.parent = (context.lang:match("^([a-z][a-z])_")) - if not tparser.load_catalog(context.lang, i18ndir) then - if context.parent then - tparser.load_catalog(context.parent, i18ndir) + local code, subcode = lang:match("^([A-Za-z][A-Za-z])[%-_]([A-Za-z][A-Za-z])$") + if not (code and subcode) then + subcode = lang:match("^([A-Za-z][A-Za-z])$") + if not subcode then + return nil + end + end + + context.parent = code and code:lower() + context.lang = context.parent and context.parent.."-"..subcode:lower() or subcode:lower() + + if tparser.load_catalog(context.lang, i18ndir) and + tparser.change_catalog(context.lang) + then + return context.lang + + elseif context.parent then + if tparser.load_catalog(context.parent, i18ndir) and + tparser.change_catalog(context.parent) + then return context.parent end end - return context.lang + + return nil end function translate(key) diff --git a/modules/luci-base/luasrc/i18n.luadoc b/modules/luci-base/luasrc/i18n.luadoc index aa38841e1..13f10a107 100644 --- a/modules/luci-base/luasrc/i18n.luadoc +++ b/modules/luci-base/luasrc/i18n.luadoc @@ -37,7 +37,8 @@ Set the context default translation language. @class function @name setlanguage -@param lang Two-letter language code +@param lang An IETF/BCP 47 language tag or ISO3166 country code, e.g. "en-US" or "de" +@return The effective loaded language, e.g. "en" for "en-US" - or nil on failure ]] ---[[ -- cgit v1.2.3