diff --git a/aurweb/l10n.py b/aurweb/l10n.py index 9270f3ce..c4938d64 100644 --- a/aurweb/l10n.py +++ b/aurweb/l10n.py @@ -93,3 +93,21 @@ def tr(context: typing.Any, value: str): """ A translation filter; example: {{ "Hello" | tr("de") }}. """ _ = get_translator_for_request(context.get("request")) return _(value) + + +@pass_context +def tn(context: typing.Dict[str, typing.Any], count: int, + singular: str, plural: str) -> str: + """ A singular and plural translation filter. + + Example: + {{ some_integer | tn("singular %d", "plural %d") }} + + :param context: Response context + :param count: The number used to decide singular or plural state + :param singular: The singular translation + :param plural: The plural translation + :return: Translated string + """ + gettext = get_raw_translator_for_request(context.get("request")) + return gettext.ngettext(singular, plural, count) diff --git a/aurweb/templates.py b/aurweb/templates.py index fa7aa039..7530472f 100644 --- a/aurweb/templates.py +++ b/aurweb/templates.py @@ -23,8 +23,9 @@ loader = jinja2.FileSystemLoader(os.path.join( env = jinja2.Environment(loader=loader, autoescape=True, extensions=["jinja2.ext.i18n"]) -# Add tr translation filter. +# Add t{r,n} translation filters. env.filters["tr"] = l10n.tr +env.filters["tn"] = l10n.tn # Utility filters. env.filters["dt"] = util.timestamp_to_datetime diff --git a/test/test_l10n.py b/test/test_l10n.py index e833cd44..1c2ae95a 100644 --- a/test/test_l10n.py +++ b/test/test_l10n.py @@ -36,3 +36,15 @@ def test_get_translator_for_request(): translate = l10n.get_translator_for_request(request) assert translate("Home") == "Startseite" + + +def test_tn_filter(): + request = Request() + request.cookies["AURLANG"] = "en" + context = {"language": "en", "request": request} + + translated = l10n.tn(context, 1, "%d package found.", "%d packages found.") + assert translated == "%d package found." + + translated = l10n.tn(context, 2, "%d package found.", "%d packages found.") + assert translated == "%d packages found."