summaryrefslogtreecommitdiffstats
path: root/venv/Lib/site-packages/flask_wtf/i18n.py
blob: 79432a1e3cd9fe0d8a4ac78b9b1f9009e4ec3049 (plain)
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
from babel import support
from flask import current_app
from flask import request
from wtforms.i18n import messages_path

try:
    from flask_babel import get_locale
except ImportError:
    from flask_babelex import get_locale

__all__ = ("Translations", "translations")


def _get_translations():
    """Returns the correct gettext translations.
    Copy from flask-babel with some modifications.
    """

    if not request:
        return None

    # babel should be in extensions for get_locale
    if "babel" not in current_app.extensions:
        return None

    translations = getattr(request, "wtforms_translations", None)

    if translations is None:
        translations = support.Translations.load(
            messages_path(), [get_locale()], domain="wtforms"
        )
        request.wtforms_translations = translations

    return translations


class Translations:
    def gettext(self, string):
        t = _get_translations()
        return string if t is None else t.ugettext(string)

    def ngettext(self, singular, plural, n):
        t = _get_translations()

        if t is None:
            return singular if n == 1 else plural

        return t.ungettext(singular, plural, n)


translations = Translations()