translations.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import os
  2. import babel
  3. from flask_babelex import Domain, get_locale
  4. from flask_plugins import get_enabled_plugins
  5. class FlaskBBDomain(Domain):
  6. def __init__(self, app):
  7. self.app = app
  8. super(FlaskBBDomain, self).__init__()
  9. self.plugins_folder = os.path.join(
  10. os.path.join(self.app.root_path, "plugins")
  11. )
  12. # FlaskBB's translations
  13. self.flaskbb_translations = os.path.join(
  14. self.app.root_path, "translations"
  15. )
  16. # Plugin translations
  17. with self.app.app_context():
  18. self.plugin_translations = [
  19. os.path.join(plugin.path, "translations")
  20. for plugin in get_enabled_plugins()
  21. ]
  22. def get_translations(self):
  23. """Returns the correct gettext translations that should be used for
  24. this request. This will never fail and return a dummy translation
  25. object if used outside of the request or if a translation cannot be
  26. found.
  27. """
  28. locale = get_locale()
  29. cache = self.get_translations_cache()
  30. translations = cache.get(str(locale))
  31. if translations is None:
  32. # load flaskbb translations
  33. translations = babel.support.Translations.load(
  34. dirname=self.flaskbb_translations,
  35. locales=locale,
  36. domain="messages"
  37. )
  38. # If no compiled translations are found, return the
  39. # NullTranslations object.
  40. if not isinstance(translations, babel.support.Translations):
  41. return translations
  42. # now load and add the plugin translations
  43. for plugin in self.plugin_translations:
  44. plugin_translation = babel.support.Translations.load(
  45. dirname=plugin,
  46. locales=locale,
  47. domain="messages"
  48. )
  49. translations.add(plugin_translation)
  50. cache[str(locale)] = translations
  51. return translations