forked from viur-framework/viur-vi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathi18n.py
83 lines (64 loc) · 2.09 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
74
75
76
77
78
79
80
81
82
83
# -*- coding: utf-8 -*-
import logging
from . import html5
from . import translations
_currentLanguage = None
if html5.jseval:
_currentLanguage = html5.jseval("navigator.language")
if not _currentLanguage:
_currentLanguage = html5.jseval("navigator.browserLanguage")
if not _currentLanguage:
_currentLanguage = "en"
if len(_currentLanguage) > 2:
_currentLanguage = _currentLanguage[:2]
logging.info("_currentLanguage is %r", _currentLanguage)
_runtimeTranslations = {}
_lngMap = {}
#Populate the lng table
for key in dir( translations ):
if key.startswith("lng"):
_lngMap[ key[3:].lower() ] = { k.lower(): v for k,v in getattr( translations, key ).items() }
def translate( key, **kwargs ):
"""
Tries to translate the given string in the currently selected language.
Supports replacing markers (using {markerName} syntax).
:param key: The string to translate
:type key: str
:returns: The translated string
"""
def processTr( inStr, **kwargs ):
for k,v in kwargs.items():
inStr = inStr.replace("{%s}" % k, str(v))
return inStr
if _currentLanguage in _runtimeTranslations.keys():
if key.lower() in _runtimeTranslations[_currentLanguage].keys():
return processTr(_runtimeTranslations[_currentLanguage][key.lower()], **kwargs)
if _currentLanguage in _lngMap.keys():
if key.lower() in _lngMap[_currentLanguage].keys():
return processTr(_lngMap[ _currentLanguage][key.lower()], **kwargs)
return processTr(key, **kwargs)
def addTranslation( lang, a, b=None ):
"""
Adds or updates new translations.
"""
if not lang in _runtimeTranslations.keys():
_runtimeTranslations[ lang ] = {}
if isinstance(a,str) and b is not None:
updateDict = { a.lower() : b }
elif isinstance( a, dict ):
updateDict = { k.lower(): v for k,v in a.items() }
else:
raise ValueError("Invalid call to addTranslation")
_runtimeTranslations[ lang ].update( updateDict )
def setLanguage( lang ):
"""
Sets the current language to lang
"""
global _currentLanguage
_currentLanguage = lang
def getLanguage():
"""
Returns the current language
"""
global _currentLanguage
return _currentLanguage