forked from mgard/epater
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathi18n.py
74 lines (63 loc) · 2.28 KB
/
i18n.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import gettext
class I18n:
"""
This class is used for internationalization without a specific language.
Objects can be stored as msgid from gettext or as str.
"""
def __init__(self, msg, isSTR=False):
if isSTR:
self.content = [msg]
else:
self.content = [self.I18n_inner(msg)]
def append(self, msg):
if type(msg) == self.__class__:
self.content += msg.content
else:
self.content.append(msg)
def __iadd__(self, msg):
self.append(msg)
return self
def format(self, *args, **kwargs):
self.content[-1].format(*args, **kwargs)
return self
def getText(self, lang):
"""
Return the localized translation
:param lang: the language to translate
"""
if type(lang) == str:
lang = gettext.translation('interpreter', './locale', languages=[lang], fallback=True)
result = ""
for msg in self.content:
if type(msg) == self.I18n_inner or type(msg) == self.__class__:
result += msg.getText(lang)
else:
result += msg
return result
# Inner class
class I18n_inner:
def __init__(self, msg):
self.msg = msg
self.formatArg = None
self.formatKwargs = None
def format(self, *args, **kwargs):
self.formatKwargs = kwargs
self.formatArg = args
return self
def getText(self, t):
if self.formatKwargs:
for key, value in self.formatKwargs.items():
if type(value) == I18n or type(value) == self.__class__:
self.formatKwargs[key] = value.getText(t)
if self.formatArg:
resultArg = []
for arg in self.formatArg:
if type(arg) == I18n or type(arg) == self.__class__:
resultArg.append(arg.getText(t))
else:
resultArg.append(arg)
return t.gettext(self.msg).format(*resultArg, **self.formatKwargs)
elif self.formatKwargs:
return t.gettext(self.msg).format(**self.formatKwargs)
else:
return t.gettext(self.msg)