i18n.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from babel import support
  2. from flask import current_app
  3. from flask import request
  4. from flask_babel import get_locale
  5. from wtforms.i18n import messages_path
  6. __all__ = ("Translations", "translations")
  7. def _get_translations():
  8. """Returns the correct gettext translations.
  9. Copy from flask-babel with some modifications.
  10. """
  11. if not request:
  12. return None
  13. # babel should be in extensions for get_locale
  14. if "babel" not in current_app.extensions:
  15. return None
  16. translations = getattr(request, "wtforms_translations", None)
  17. if translations is None:
  18. translations = support.Translations.load(
  19. messages_path(), [get_locale()], domain="wtforms"
  20. )
  21. request.wtforms_translations = translations
  22. return translations
  23. class Translations:
  24. def gettext(self, string):
  25. t = _get_translations()
  26. return string if t is None else t.ugettext(string)
  27. def ngettext(self, singular, plural, n):
  28. t = _get_translations()
  29. if t is None:
  30. return singular if n == 1 else plural
  31. return t.ungettext(singular, plural, n)
  32. translations = Translations()