1from babel import support
2from flask import current_app, request
3from wtforms.i18n import messages_path
4
5try:
6    from flask_babel import get_locale
7except ImportError:
8    from flask_babelex import get_locale
9
10__all__ = ('Translations', 'translations')
11
12
13def _get_translations():
14    """Returns the correct gettext translations.
15    Copy from flask-babel with some modifications.
16    """
17
18    if not request:
19        return None
20
21    # babel should be in extensions for get_locale
22    if 'babel' not in current_app.extensions:
23        return None
24
25    translations = getattr(request, 'wtforms_translations', None)
26
27    if translations is None:
28        translations = support.Translations.load(
29            messages_path(), [get_locale()], domain='wtforms'
30        )
31        request.wtforms_translations = translations
32
33    return translations
34
35
36class Translations:
37    def gettext(self, string):
38        t = _get_translations()
39        return string if t is None else t.ugettext(string)
40
41    def ngettext(self, singular, plural, n):
42        t = _get_translations()
43
44        if t is None:
45            return singular if n == 1 else plural
46
47        return t.ungettext(singular, plural, n)
48
49
50translations = Translations()
51