mirror of
https://gitlab.archlinux.org/archlinux/aurweb.git
synced 2025-02-03 10:43:03 +01:00
jinja2: add 'tn' filter, a numerical translation
The possibly plural version of `tr`, `tn` provides a way to translate strings into singular or plural form based on a given integer being 1 or not 1. Example use: ``` {{ 1 | tn("%d package found.", "%d packages found.") | format(1) }} ``` Signed-off-by: Kevin Morris <kevr@0cost.org>
This commit is contained in:
parent
1c26ce52a5
commit
45fbf214b4
3 changed files with 32 additions and 1 deletions
|
@ -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)
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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."
|
||||
|
|
Loading…
Add table
Reference in a new issue