babel.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. try:
  2. from flask_babelex import Domain
  3. except ImportError:
  4. def gettext(string, **variables):
  5. return string % variables
  6. def ngettext(singular, plural, num, **variables):
  7. variables.setdefault('num', num)
  8. return (singular if num == 1 else plural) % variables
  9. def lazy_gettext(string, **variables):
  10. return gettext(string, **variables)
  11. class Translations(object):
  12. ''' dummy Translations class for WTForms, no translation support '''
  13. def gettext(self, string):
  14. return string
  15. def ngettext(self, singular, plural, n):
  16. return singular if n == 1 else plural
  17. else:
  18. from flask_admin import translations
  19. class CustomDomain(Domain):
  20. def __init__(self):
  21. super(CustomDomain, self).__init__(translations.__path__[0], domain='admin')
  22. def get_translations_path(self, ctx):
  23. view = get_current_view()
  24. if view is not None:
  25. dirname = view.admin.translations_path
  26. if dirname is not None:
  27. return dirname
  28. return super(CustomDomain, self).get_translations_path(ctx)
  29. domain = CustomDomain()
  30. gettext = domain.gettext
  31. ngettext = domain.ngettext
  32. lazy_gettext = domain.lazy_gettext
  33. try:
  34. from wtforms.i18n import messages_path
  35. except ImportError:
  36. from wtforms.ext.i18n.utils import messages_path
  37. wtforms_domain = Domain(messages_path(), domain='wtforms')
  38. class Translations(object):
  39. ''' Fixes WTForms translation support and uses wtforms translations '''
  40. def gettext(self, string):
  41. t = wtforms_domain.get_translations()
  42. return t.ugettext(string)
  43. def ngettext(self, singular, plural, n):
  44. t = wtforms_domain.get_translations()
  45. return t.ungettext(singular, plural, n)
  46. # lazy imports
  47. from .helpers import get_current_view