Merge pull request #1126 from imomaliev/pgettext-support
Before adoption: this commit came in with the history the project adopted, so no landing records it.
add pgettext to InternationalizationExtension
authored by Adrian · committed by GitHub · parents beabf30, 3fba898 · Browse files · 4 files·+168 added−24 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+168 added−24 removed
- tests:+81 added−8 removed
- other:+87 added−16 removed
Provenance
- Commit
43d4228- Tree
45e4af2- Author
Adrian <adrian@planetcoding.net>- Committer
GitHub <noreply@github.com>- Parent 1
beabf30- Parent 2
3fba898
4 files changed+168 added−24 removed
modified:docs/extensions.rst+28 added-10 removed
32 unmodified lines33 The i18n extension can be used in combination with `gettext`_ or34 `Babel`_. When it's enabled, Jinja provides a ``trans`` statement that35 marks a block as translatable and calls ``gettext``.36 37-After enabling, an application has to provide ``gettext`` and38-``ngettext`` functions, either globally or when rendering. A ``_()``39-function is added as an alias to the ``gettext`` function.37+After enabling, an application has to provide functions for ``gettext``,38+``ngettext``, and optionally ``pgettext`` and ``npgettext``, either39+globally or when rendering. A ``_()`` function is added as an alias to40+the ``gettext`` function.41 42+43 Environment Methods44 ~~~~~~~~~~~~~~~~~~~45 46 After enabling the extension, the environment provides the following1 unmodified line48 49 .. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)50 51 Installs a translation globally for the environment. The50- ``translations`` object must implement ``gettext`` and ``ngettext``.52+ ``translations`` object must implement ``gettext``, ``ngettext``,53+ and optionally ``pgettext`` and ``npgettext``.54 :class:`gettext.NullTranslations`, :class:`gettext.GNUTranslations`,55 and `Babel`_\s ``Translations`` are supported.56 54- .. versionchanged:: 2.5 Added new-style gettext support.57+ .. versionchanged:: 3.058+ Added ``pgettext`` and ``npgettext``.59 60+ .. versionchanged:: 2.561+ Added new-style gettext support.62+63 .. method:: jinja2.Environment.install_null_translations(newstyle=False)64 65 Install no-op gettext functions. This is useful if you want to66 prepare the application for internationalization but don't want to67 implement the full system yet.68 69 .. versionchanged:: 2.5 Added new-style gettext support.70 64-.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)71+.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False, pgettext=None, npgettext=None)72 66- Install the given ``gettext`` and ``ngettext`` callables into the67- environment. They should behave exactly like68- :func:`gettext.gettext` and :func:`gettext.ngettext`.73+ Install the given ``gettext``, ``ngettext``, ``pgettext``, and74+ ``npgettext`` callables into the environment. They should behave75+ exactly like :func:`gettext.gettext`, :func:`gettext.ngettext`,76+ :func:`gettext.pgettext` and :func:`gettext.npgettext`.77 78 If ``newstyle`` is activated, the callables are wrapped to work like79 newstyle callables. See :ref:`newstyle-gettext` for more information.80 73- .. versionadded:: 2.5 Added new-style gettext support.81+ .. versionchanged:: 3.082+ Added ``pgettext`` and ``npgettext``.83 84+ .. versionadded:: 2.585+ Added new-style gettext support.86+87 .. method:: jinja2.Environment.uninstall_gettext_translations()88 89 Uninstall the environment's globally installed translation.90 74 unmodified lines165 {{ gettext("Hello, %(name)s!")|format(name=name) }}166 {{ ngettext(167 "%(num)d apple", "%(num)d apples", apples|count168 )|format(num=apples|count) }}169+ {{ pgettext("greeting", "Hello, World!") }}170+ {{ npgettext(171+ "fruit", "%(num)d apple", "%(num)d apples", apples|count172+ )|format(num=apples|count) }}173 174 New style ``gettext`` make formatting part of the call, and behind the175 scenes enforce more consistency.176 1 unmodified line178 179 {{ gettext("Hello, World!") }}180 {{ gettext("Hello, %(name)s!", name=name) }}181 {{ ngettext("%(num)d apple", "%(num)d apples", apples|count) }}182+ {{ pgettext("greeting", "Hello, World!") }}183+ {{ npgettext("fruit", "%(num)d apple", "%(num)d apples", apples|count) }}184 185 The advantages of newstyle gettext are:186 187 - There's no separate formatting step, you don't have to remember to236 unmodified linesmodified:src/jinja2/ext.py+57 added-6 removed
28 unmodified lines29 from .utils import import_string30 31 # I18N functions available in Jinja templates. If the I18N library32 # provides ugettext, it will be assigned to gettext.33-GETTEXT_FUNCTIONS = ("_", "gettext", "ngettext")33+GETTEXT_FUNCTIONS = ("_", "gettext", "ngettext", "pgettext", "npgettext")34 _ws_re = re.compile(r"\s*\n\s*")35 36 37 class ExtensionRegistry(type):128 unmodified lines166 167 return ngettext168 169 170+def _make_new_pgettext(func):171+ @contextfunction172+ def pgettext(__context, __string_ctx, __string, **variables):173+ variables.setdefault("context", __string_ctx)174+ rv = __context.call(func, __string_ctx, __string)175+176+ if __context.eval_ctx.autoescape:177+ rv = Markup(rv)178+179+ # Always treat as a format string, see gettext comment above.180+ return rv % variables181+182+ return pgettext183+184+185+def _make_new_npgettext(func):186+ @contextfunction187+ def npgettext(__context, __string_ctx, __singular, __plural, __num, **variables):188+ variables.setdefault("context", __string_ctx)189+ variables.setdefault("num", __num)190+ rv = __context.call(func, __string_ctx, __singular, __plural, __num)191+192+ if __context.eval_ctx.autoescape:193+ rv = Markup(rv)194+195+ # Always treat as a format string, see gettext comment above.196+ return rv % variables197+198+ return npgettext199+200+201 class InternationalizationExtension(Extension):202 """This extension adds gettext support to Jinja."""203 204 tags = {"trans"}25 unmodified lines230 gettext = translations.gettext231 ngettext = getattr(translations, "ungettext", None)232 if ngettext is None:233 ngettext = translations.ngettext203- self._install_callables(gettext, ngettext, newstyle)234 235+ pgettext = getattr(translations, "pgettext", None)236+ npgettext = getattr(translations, "npgettext", None)237+ self._install_callables(238+ gettext, ngettext, newstyle=newstyle, pgettext=pgettext, npgettext=npgettext239+ )240+241 def _install_null(self, newstyle=None):242 self._install_callables(207- lambda x: x, lambda s, p, n: s if n == 1 else p, newstyle243+ lambda s: s,244+ lambda s, p, n: s if n == 1 else p,245+ newstyle=newstyle,246+ pgettext=lambda c, s: s,247+ npgettext=lambda c, s, p, n: s if n == 1 else p,248 )249 210- def _install_callables(self, gettext, ngettext, newstyle=None):250+ def _install_callables(251+ self, gettext, ngettext, newstyle=None, pgettext=None, npgettext=None252+ ):253 if newstyle is not None:254 self.environment.newstyle_gettext = newstyle255 if self.environment.newstyle_gettext:256 gettext = _make_new_gettext(gettext)257 ngettext = _make_new_ngettext(ngettext)216- self.environment.globals.update(gettext=gettext, ngettext=ngettext)258 259+ if pgettext is not None:260+ pgettext = _make_new_pgettext(pgettext)261+262+ if npgettext is not None:263+ npgettext = _make_new_npgettext(npgettext)264+265+ self.environment.globals.update(266+ gettext=gettext, ngettext=ngettext, pgettext=pgettext, npgettext=npgettext267+ )268+269 def _uninstall(self, translations):219- for key in "gettext", "ngettext":270+ for key in ("gettext", "ngettext", "pgettext", "npgettext"):271 self.environment.globals.pop(key, None)272 273 def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):274 if isinstance(source, str):493 unmodified linesmodified:tests/test_ext.py+81 added-8 removed
38 unmodified lines39 "stringformat.html": '{{ _("User: %(num)s", num=user_count) }}',40 "ngettext.html": '{{ ngettext("%(num)s apple", "%(num)s apples", apples) }}',41 "ngettext_long.html": "{% trans num=apples %}{{ num }} apple{% pluralize %}"42 "{{ num }} apples{% endtrans %}",43+ "pgettext.html": '{{ pgettext("fruit", "Apple") }}',44+ "npgettext.html": '{{ npgettext("fruit", "%(num)s apple", "%(num)s apples",'45+ " apples) }}",46 "transvars1.html": "{% trans %}User: {{ num }}{% endtrans %}",47 "transvars2.html": "{% trans num=count %}User: {{ num }}{% endtrans %}",48 "transvars3.html": "{% trans count=num %}User: {{ count }}{% endtrans %}",49 "novars.html": "{% trans %}%(hello)s{% endtrans %}",9 unmodified lines59 "One user online": "Ein Benutzer online",60 "%(user_count)s users online": "%(user_count)s Benutzer online",61 "User: %(num)s": "Benutzer: %(num)s",62 "User: %(count)s": "Benutzer: %(count)s",60- "%(num)s apple": "%(num)s Apfel",61- "%(num)s apples": "%(num)s Äpfel",63+ "Apple": {None: "Apfel", "fruit": "Apple"},64+ "%(num)s apple": {None: "%(num)s Apfel", "fruit": "%(num)s Apple"},65+ "%(num)s apples": {None: "%(num)s Äpfel", "fruit": "%(num)s Apples"},66 }67 }68 69 70+def _get_with_context(value, ctx=None):71+ if isinstance(value, dict):72+ return value.get(ctx, value)73+74+ return value75+76+77 @contextfunction78 def gettext(context, string):79 language = context.get("LANGUAGE", "en")69- return languages.get(language, {}).get(string, string)80+ value = languages.get(language, {}).get(string, string)81+ return _get_with_context(value)82 83 84 @contextfunction85 def ngettext(context, s, p, n):86 language = context.get("LANGUAGE", "en")87+88 if n != 1:76- return languages.get(language, {}).get(p, p)77- return languages.get(language, {}).get(s, s)89+ value = languages.get(language, {}).get(p, p)90+ return _get_with_context(value)91 92+ value = languages.get(language, {}).get(s, s)93+ return _get_with_context(value)94 95+96+@contextfunction97+def pgettext(context, c, s):98+ language = context.get("LANGUAGE", "en")99+ value = languages.get(language, {}).get(s, s)100+ return _get_with_context(value, c)101+102+103+@contextfunction104+def npgettext(context, c, s, p, n):105+ language = context.get("LANGUAGE", "en")106+107+ if n != 1:108+ value = languages.get(language, {}).get(p, p)109+ return _get_with_context(value, c)110+111+ value = languages.get(language, {}).get(s, s)112+ return _get_with_context(value, c)113+114+115 i18n_env = Environment(116 loader=DictLoader(i18n_templates), extensions=["jinja2.ext.i18n"]117 )83-i18n_env.globals.update({"_": gettext, "gettext": gettext, "ngettext": ngettext})118+i18n_env.globals.update(119+ {120+ "_": gettext,121+ "gettext": gettext,122+ "ngettext": ngettext,123+ "pgettext": pgettext,124+ "npgettext": npgettext,125+ }126+)127 i18n_env_trimmed = Environment(extensions=["jinja2.ext.i18n"])128+129 i18n_env_trimmed.policies["ext.i18n.trimmed"] = True130 i18n_env_trimmed.globals.update(87- {"_": gettext, "gettext": gettext, "ngettext": ngettext}131+ {132+ "_": gettext,133+ "gettext": gettext,134+ "ngettext": ngettext,135+ "pgettext": pgettext,136+ "npgettext": npgettext,137+ }138 )139 140 newstyle_i18n_env = Environment(141 loader=DictLoader(newstyle_i18n_templates), extensions=["jinja2.ext.i18n"]142 )143 newstyle_i18n_env.install_gettext_callables( # type: ignore94- gettext, ngettext, newstyle=True144+ gettext, ngettext, newstyle=True, pgettext=pgettext, npgettext=npgettext145 )146 147 148 class ExampleExtension(Extension):301 unmodified lines450 (4, "gettext", "Hello World", ["second"]),451 (6, "ngettext", ("%(users)s user", "%(users)s users", None), ["third"]),452 ]453 454+ def test_extract_context(self):455+ from jinja2.ext import babel_extract456 457+ source = BytesIO(458+ b"""459+ {{ pgettext("babel", "Hello World") }}460+ {{ npgettext("babel", "%(users)s user", "%(users)s users", users) }}461+ """462+ )463+ assert list(babel_extract(source, ("pgettext", "npgettext", "_"), [], {})) == [464+ (2, "pgettext", ("babel", "Hello World"), []),465+ (3, "npgettext", ("babel", "%(users)s user", "%(users)s users", None), []),466+ ]467+468+469 class TestScope:470 def test_basic_scope_behavior(self):471 # This is what the old with statement compiled down to472 class ScopeExt(Extension):115 unmodified lines588 assert t.render(foo="42") == "42%(foo)s"589 t = newstyle_i18n_env.get_template("explicitvars.html")590 assert t.render() == "%(foo)s"591 592+ def test_context(self):593+ tmpl = newstyle_i18n_env.get_template("pgettext.html")594+ assert tmpl.render(LANGUAGE="de") == "Apple"595 596+ def test_context_newstyle_plural(self):597+ tmpl = newstyle_i18n_env.get_template("npgettext.html")598+ assert tmpl.render(LANGUAGE="de", apples=1) == "1 Apple"599+ assert tmpl.render(LANGUAGE="de", apples=5) == "5 Apples"600+601+602 class TestAutoEscape:603 def test_scoped_setting(self):604 env = Environment(autoescape=True)605 tmpl = env.from_string(109 unmodified linesmodified:CHANGES.rst+2 added
44 unmodified lines45 registered filter or test. This allows checking if a filter is46 available in a template before using it. Test functions can be47 decorated with ``@environmentfunction``, ``@evalcontextfunction``,48 or ``@contextfunction``. :issue:`842`, :pr:`1248`49+- Support ``pgettext`` and ``npgettext`` (message contexts) in i18n50+ extension. :issue:`441`51 52 53 Version 2.11.354 --------------780 unmodified lines