Skip to content

Commit

Permalink
Add domain parameter to GettextWrapper and pass languages to translat…
Browse files Browse the repository at this point in the history
…ion method explicitely
  • Loading branch information
insolor committed Jan 14, 2025
1 parent f875da5 commit 6f5b317
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions streamlit_gettext/streamlit_gettext.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,13 @@
import gettext as _gettext_module
import re
from pathlib import Path
from typing import TYPE_CHECKING

import streamlit as st

if TYPE_CHECKING:
from collections.abc import Iterable


def get_preferred_languages() -> list[str]:
accept_language = st.context.headers.get("Accept-Language") or ""
Expand All @@ -16,24 +20,25 @@ class GettextWrapper:
"""
A wrapper for the gettext module
"""

locale_path: Path
domain: str

def __init__(self, locale_path: str | Path) -> None:
def __init__(self, locale_path: str | Path, domain: str = "messages") -> None:
self.locale_path = Path(locale_path)
self.domain = domain

def _translation(self) -> _gettext_module.NullTranslations:
def translation(self, languages: Iterable[str] | None = None) -> _gettext_module.NullTranslations:
return _gettext_module.translation(
"messages",
domain=self.domain,
localedir=self.locale_path,
languages=get_preferred_languages(),
languages=languages,
fallback=True,
)

def gettext(self, message: str) -> str:
translation = self._translation()
translation = self.translation(get_preferred_languages())
return translation.gettext(message)

def ngettext(self, singular: str, plural: str, n: int) -> str:
translation = self._translation()
translation = self.translation(get_preferred_languages())
return translation.ngettext(singular, plural, n)

0 comments on commit 6f5b317

Please sign in to comment.