luci-base: fix luci.i18n.setlanguage()
authorJo-Philipp Wich <jo@mein.io>
Thu, 18 Oct 2018 07:52:07 +0000 (09:52 +0200)
committerJo-Philipp Wich <jo@mein.io>
Mon, 5 Nov 2018 10:01:45 +0000 (11:01 +0100)
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>
modules/luci-base/luasrc/i18n.lua
modules/luci-base/luasrc/i18n.luadoc

index bcb16d5c04cb5ac7c90ff07dd00c75a641d0a1b2..968c387f12b6ec785264c8aa2deb3770a520504c 100644 (file)
@@ -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)
index aa38841e17b0daa80ed561e4422f2245b6069c70..13f10a107125c939db8bbffd635d939438dea102 100644 (file)
@@ -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
 ]]
 
 ---[[