e3011620210010084c6ef2b29f6fd4a80dc85428
[project/luci.git] / libs / web / luasrc / i18n.lua
1 --[[
2 LuCI - Internationalisation
3
4 Description:
5 A very minimalistic but yet effective internationalisation module
6
7 FileId:
8 $Id$
9
10 License:
11 Copyright 2008 Steven Barth <steven@midlink.org>
12
13 Licensed under the Apache License, Version 2.0 (the "License");
14 you may not use this file except in compliance with the License.
15 You may obtain a copy of the License at
16
17 http://www.apache.org/licenses/LICENSE-2.0
18
19 Unless required by applicable law or agreed to in writing, software
20 distributed under the License is distributed on an "AS IS" BASIS,
21 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 See the License for the specific language governing permissions and
23 limitations under the License.
24
25 ]]--
26
27 module("luci.i18n", package.seeall)
28 require("luci.sys")
29
30 table = {}
31 i18ndir = luci.sys.libpath() .. "/i18n/"
32 loaded = {}
33 context = luci.util.threadlocal()
34 default = "en"
35
36 -- Clears the translation table
37 function clear()
38 table = {}
39 end
40
41 -- Loads a translation and copies its data into the global translation table
42 function load(file, lang, force)
43 lang = lang or ""
44 if force or not loaded[lang] or not loaded[lang][file] then
45 local f = loadfile(i18ndir .. file .. "." .. lang .. ".lua")
46 if f then
47 table[lang] = table[lang] or {}
48 setfenv(f, table[lang])
49 f()
50 loaded[lang] = loaded[lang] or {}
51 loaded[lang][file] = true
52 return true
53 else
54 return false
55 end
56 else
57 return true
58 end
59 end
60
61 -- Same as load but autocompletes the filename with .LANG from config.lang
62 function loadc(file, force)
63 load(file, default, force)
64 return load(file, context.lang, force)
65 end
66
67 -- Sets the context language
68 function setlanguage(lang)
69 context.lang = lang
70 end
71
72 -- Returns the i18n-value defined by "key" or if there is no such: "default"
73 function translate(key, def)
74 return (table[context.lang] and table[context.lang][key])
75 or (table[default] and table[default][key])
76 or def
77 end
78
79 -- Translate shourtcut with sprintf/string.format inclusion
80 function translatef(key, default, ...)
81 return translate(key, default):format(...)
82 end