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 <jo@mein.io>
This commit is contained in:
Jo-Philipp Wich 2018-10-18 09:52:07 +02:00
parent 62102f4f0e
commit 08255e266b
2 changed files with 24 additions and 7 deletions

View file

@ -23,15 +23,31 @@ function loadc(file, force)
end end
function setlanguage(lang) function setlanguage(lang)
context.lang = lang:gsub("_", "-") local code, subcode = lang:match("^([A-Za-z][A-Za-z])[%-_]([A-Za-z][A-Za-z])$")
context.parent = (context.lang:match("^([a-z][a-z])_")) if not (code and subcode) then
if not tparser.load_catalog(context.lang, i18ndir) then subcode = lang:match("^([A-Za-z][A-Za-z])$")
if context.parent then if not subcode then
tparser.load_catalog(context.parent, i18ndir) 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 return context.parent
end end
end end
return context.lang
return nil
end end
function translate(key) function translate(key)

View file

@ -37,7 +37,8 @@ Set the context default translation language.
@class function @class function
@name setlanguage @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
]] ]]
---[[ ---[[