Loads translations from `gettext`'s locale tree Locale tree is similar to system's ``/usr/share/locale``, like:: {directory}/{lang}/LC_MESSAGES/{domain}.mo Three steps are required to have your app translated: 1. Generate POT translation file:: xgettext --language=Py
(directory: str, domain: str)
| 175 | |
| 176 | |
| 177 | def load_gettext_translations(directory: str, domain: str) -> None: |
| 178 | """Loads translations from `gettext`'s locale tree |
| 179 | |
| 180 | Locale tree is similar to system's ``/usr/share/locale``, like:: |
| 181 | |
| 182 | {directory}/{lang}/LC_MESSAGES/{domain}.mo |
| 183 | |
| 184 | Three steps are required to have your app translated: |
| 185 | |
| 186 | 1. Generate POT translation file:: |
| 187 | |
| 188 | xgettext --language=Python --keyword=_:1,2 -d mydomain file1.py file2.html etc |
| 189 | |
| 190 | 2. Merge against existing POT file:: |
| 191 | |
| 192 | msgmerge old.po mydomain.po > new.po |
| 193 | |
| 194 | 3. Compile:: |
| 195 | |
| 196 | msgfmt mydomain.po -o {directory}/pt_BR/LC_MESSAGES/mydomain.mo |
| 197 | """ |
| 198 | global _translations |
| 199 | global _supported_locales |
| 200 | global _use_gettext |
| 201 | _translations = {} |
| 202 | |
| 203 | for filename in glob.glob( |
| 204 | os.path.join(directory, "*", "LC_MESSAGES", domain + ".mo") |
| 205 | ): |
| 206 | lang = os.path.basename(os.path.dirname(os.path.dirname(filename))) |
| 207 | try: |
| 208 | _translations[lang] = gettext.translation( |
| 209 | domain, directory, languages=[lang] |
| 210 | ) |
| 211 | except Exception as e: |
| 212 | gen_log.error("Cannot load translation for '%s': %s", lang, str(e)) |
| 213 | continue |
| 214 | _supported_locales = frozenset(list(_translations.keys()) + [_default_locale]) |
| 215 | _use_gettext = True |
| 216 | gen_log.debug("Supported locales: %s", sorted(_supported_locales)) |
| 217 | |
| 218 | |
| 219 | def get_supported_locales() -> Iterable[str]: |