luci-base: fix luci.i18n.setlanguage()
[oweals/luci.git] / modules / luci-base / luasrc / i18n.lua
1 -- Copyright 2008 Steven Barth <steven@midlink.org>
2 -- Licensed to the public under the Apache License 2.0.
3
4 module("luci.i18n", package.seeall)
5 require("luci.util")
6
7 local tparser = require "luci.template.parser"
8
9 table   = {}
10 i18ndir = luci.util.libpath() .. "/i18n/"
11 loaded  = {}
12 context = luci.util.threadlocal()
13 default = "en"
14
15 function clear()
16 end
17
18 function load(file, lang, force)
19 end
20
21 -- Alternatively load the translation of the fallback language.
22 function loadc(file, force)
23 end
24
25 function setlanguage(lang)
26         local code, subcode = lang:match("^([A-Za-z][A-Za-z])[%-_]([A-Za-z][A-Za-z])$")
27         if not (code and subcode) then
28                 subcode = lang:match("^([A-Za-z][A-Za-z])$")
29                 if not subcode then
30                         return nil
31                 end
32         end
33
34         context.parent = code and code:lower()
35         context.lang   = context.parent and context.parent.."-"..subcode:lower() or subcode:lower()
36
37         if tparser.load_catalog(context.lang, i18ndir) and
38            tparser.change_catalog(context.lang)
39         then
40                 return context.lang
41
42         elseif context.parent then
43                 if tparser.load_catalog(context.parent, i18ndir) and
44                    tparser.change_catalog(context.parent)
45                 then
46                         return context.parent
47                 end
48         end
49
50         return nil
51 end
52
53 function translate(key)
54         return tparser.translate(key) or key
55 end
56
57 function translatef(key, ...)
58         return tostring(translate(key)):format(...)
59 end
60
61 -- and ensure that the returned value is a Lua string value.
62 -- This is the same as calling <code>tostring(translate(...))</code>
63 function string(key)
64         return tostring(translate(key))
65 end
66
67 -- Ensure that the returned value is a Lua string value.
68 -- This is the same as calling <code>tostring(translatef(...))</code>
69 function stringf(key, ...)
70         return tostring(translate(key)):format(...)
71 end