2 LuCI - Internationalisation
5 A very minimalistic but yet effective internationalisation module
11 Copyright 2008 Steven Barth <steven@midlink.org>
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
17 http://www.apache.org/licenses/LICENSE-2.0
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.
27 --- LuCI translation library.
28 module("luci.i18n", package.seeall)
33 i18ndir = luci.util.libpath() .. "/i18n/"
35 context = luci.util.threadlocal()
38 --- Clear the translation table.
43 --- Load a translation and copy its data into the translation table.
44 -- @param file Language file
45 -- @param lang Two-letter language code
46 -- @param force Force reload even if already loaded (optional)
47 -- @return Success status
48 function load(file, lang, force)
49 lang = lang and lang:gsub("_", "-") or ""
50 if force or not loaded[lang] or not loaded[lang][file] then
51 local f = lmo.open(i18ndir .. file .. "." .. lang .. ".lmo")
53 if not table[lang] then
55 setmetatable(table[lang], {
56 __index = function(tbl, key)
58 local s = rawget(tbl, i):lookup(key)
59 if s then return s end
64 table[lang][#table[lang]+1] = f
67 loaded[lang] = loaded[lang] or {}
68 loaded[lang][file] = true
78 --- Load a translation file using the default translation language.
79 -- Alternatively load the translation of the fallback language.
80 -- @param file Language file
81 -- @param force Force reload even if already loaded (optional)
82 function loadc(file, force)
83 load(file, default, force)
84 if context.parent then load(file, context.parent, force) end
85 return load(file, context.lang, force)
88 --- Set the context default translation language.
89 -- @param lang Two-letter language code
90 function setlanguage(lang)
91 context.lang = lang:gsub("_", "-")
92 context.parent = (context.lang:match("^([a-z][a-z])_"))
95 --- Return the translated value for a specific translation key.
96 -- @param key Translation key
97 -- @param def Default translation
98 -- @return Translated string
99 function translate(key, def)
100 return (table[context.lang] and table[context.lang][key])
101 or (table[context.parent] and table[context.parent][key])
102 or (table[default] and table[default][key])
106 --- Return the translated value for a specific translation key and use it as sprintf pattern.
107 -- @param key Translation key
108 -- @param default Default translation
109 -- @param ... Format parameters
110 -- @return Translated and formatted string
111 function translatef(key, default, ...)
112 return translate(key, default):format(...)