luci-base: move tools.webadmin to luci-compat
[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 local tparser  = require "luci.template.parser"
5 local util     = require "luci.util"
6 local tostring = tostring
7
8 module "luci.i18n"
9
10 i18ndir = util.libpath() .. "/i18n/"
11 context = util.threadlocal()
12 default = "en"
13
14
15 function setlanguage(lang)
16         local code, subcode = lang:match("^([A-Za-z][A-Za-z])[%-_]([A-Za-z][A-Za-z])$")
17         if not (code and subcode) then
18                 subcode = lang:match("^([A-Za-z][A-Za-z])$")
19                 if not subcode then
20                         return nil
21                 end
22         end
23
24         context.parent = code and code:lower()
25         context.lang   = context.parent and context.parent.."-"..subcode:lower() or subcode:lower()
26
27         if tparser.load_catalog(context.lang, i18ndir) and
28            tparser.change_catalog(context.lang)
29         then
30                 return context.lang
31
32         elseif context.parent then
33                 if tparser.load_catalog(context.parent, i18ndir) and
34                    tparser.change_catalog(context.parent)
35                 then
36                         return context.parent
37                 end
38         end
39
40         return nil
41 end
42
43 function translate(key)
44         return tparser.translate(key) or key
45 end
46
47 function translatef(key, ...)
48         return tostring(translate(key)):format(...)
49 end
50
51 function dump()
52         local rv = {}
53         tparser.get_translations(function(k, v) rv[k] = v end)
54         return rv
55 end