Skip to content
Myr

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

4 files+168 added−24 removed

modified:docs/extensions.rst+28 added-10 removed
32 unmodified lines
33The i18n extension can be used in combination with `gettext`_ or34`Babel`_. When it's enabled, Jinja provides a ``trans`` statement that35marks a block as translatable and calls ``gettext``.3637After enabling, an application has to provide ``gettext`` and38``ngettext`` functions, either globally or when rendering. A ``_()``39function is added as an alias to the ``gettext`` function.37After enabling, an application has to provide functions for ``gettext``,38``ngettext``, and optionally ``pgettext`` and ``npgettext``, either39globally or when rendering. A ``_()`` function is added as an alias to40the ``gettext`` function.414243Environment Methods44~~~~~~~~~~~~~~~~~~~4546After enabling the extension, the environment provides the following
1 unmodified line
4849.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)5051 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.5654 .. versionchanged:: 2.5 Added new-style gettext support.57 .. versionchanged:: 3.058 Added ``pgettext`` and ``npgettext``.5960 .. versionchanged:: 2.561 Added new-style gettext support.6263.. method:: jinja2.Environment.install_null_translations(newstyle=False)6465 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.6869 .. versionchanged:: 2.5 Added new-style gettext support.7064.. 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)7266 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`.7778 If ``newstyle`` is activated, the callables are wrapped to work like79 newstyle callables. See :ref:`newstyle-gettext` for more information.8073 .. versionadded:: 2.5 Added new-style gettext support.81 .. versionchanged:: 3.082 Added ``pgettext`` and ``npgettext``.8384 .. versionadded:: 2.585 Added new-style gettext support.8687.. method:: jinja2.Environment.uninstall_gettext_translations()8889 Uninstall the environment's globally installed translation.90
74 unmodified lines
165 {{ 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) }}173174New style ``gettext`` make formatting part of the call, and behind the175scenes enforce more consistency.176
1 unmodified line
178179 {{ 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) }}184185The advantages of newstyle gettext are:186187- There's no separate formatting step, you don't have to remember to
236 unmodified lines
modified:src/jinja2/ext.py+57 added-6 removed
28 unmodified lines
29from .utils import import_string3031# I18N functions available in Jinja templates. If the I18N library32# provides ugettext, it will be assigned to gettext.33GETTEXT_FUNCTIONS = ("_", "gettext", "ngettext")33GETTEXT_FUNCTIONS = ("_", "gettext", "ngettext", "pgettext", "npgettext")34_ws_re = re.compile(r"\s*\n\s*")353637class ExtensionRegistry(type):
128 unmodified lines
166167 return ngettext168169170def _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)175176 if __context.eval_ctx.autoescape:177 rv = Markup(rv)178179 # Always treat as a format string, see gettext comment above.180 return rv % variables181182 return pgettext183184185def _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)191192 if __context.eval_ctx.autoescape:193 rv = Markup(rv)194195 # Always treat as a format string, see gettext comment above.196 return rv % variables197198 return npgettext199200201class InternationalizationExtension(Extension):202 """This extension adds gettext support to Jinja."""203204 tags = {"trans"}
25 unmodified lines
230 gettext = translations.gettext231 ngettext = getattr(translations, "ungettext", None)232 if ngettext is None:233 ngettext = translations.ngettext203 self._install_callables(gettext, ngettext, newstyle)234235 pgettext = getattr(translations, "pgettext", None)236 npgettext = getattr(translations, "npgettext", None)237 self._install_callables(238 gettext, ngettext, newstyle=newstyle, pgettext=pgettext, npgettext=npgettext239 )240241 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 )249210 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)258259 if pgettext is not None:260 pgettext = _make_new_pgettext(pgettext)261262 if npgettext is not None:263 npgettext = _make_new_npgettext(npgettext)264265 self.environment.globals.update(266 gettext=gettext, ngettext=ngettext, pgettext=pgettext, npgettext=npgettext267 )268269 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)272273 def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):274 if isinstance(source, str):
493 unmodified lines
modified:tests/test_ext.py+81 added-8 removed
38 unmodified lines
39 "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 lines
59 "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}686970def _get_with_context(value, ctx=None):71 if isinstance(value, dict):72 return value.get(ctx, value)7374 return value757677@contextfunction78def 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)828384@contextfunction85def ngettext(context, s, p, n):86 language = context.get("LANGUAGE", "en")8788 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)9192 value = languages.get(language, {}).get(s, s)93 return _get_with_context(value)949596@contextfunction97def 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)101102103@contextfunction104def npgettext(context, c, s, p, n):105 language = context.get("LANGUAGE", "en")106107 if n != 1:108 value = languages.get(language, {}).get(p, p)109 return _get_with_context(value, c)110111 value = languages.get(language, {}).get(s, s)112 return _get_with_context(value, c)113114115i18n_env = Environment(116 loader=DictLoader(i18n_templates), extensions=["jinja2.ext.i18n"]117)83i18n_env.globals.update({"_": gettext, "gettext": gettext, "ngettext": ngettext})118i18n_env.globals.update(119 {120 "_": gettext,121 "gettext": gettext,122 "ngettext": ngettext,123 "pgettext": pgettext,124 "npgettext": npgettext,125 }126)127i18n_env_trimmed = Environment(extensions=["jinja2.ext.i18n"])128129i18n_env_trimmed.policies["ext.i18n.trimmed"] = True130i18n_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)139140newstyle_i18n_env = Environment(141 loader=DictLoader(newstyle_i18n_templates), extensions=["jinja2.ext.i18n"]142)143newstyle_i18n_env.install_gettext_callables( # type: ignore94 gettext, ngettext, newstyle=True144 gettext, ngettext, newstyle=True, pgettext=pgettext, npgettext=npgettext145)146147148class ExampleExtension(Extension):
301 unmodified lines
450 (4, "gettext", "Hello World", ["second"]),451 (6, "ngettext", ("%(users)s user", "%(users)s users", None), ["third"]),452 ]453454 def test_extract_context(self):455 from jinja2.ext import babel_extract456457 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 ]467468469class TestScope:470 def test_basic_scope_behavior(self):471 # This is what the old with statement compiled down to472 class ScopeExt(Extension):
115 unmodified lines
588 assert t.render(foo="42") == "42%(foo)s"589 t = newstyle_i18n_env.get_template("explicitvars.html")590 assert t.render() == "%(foo)s"591592 def test_context(self):593 tmpl = newstyle_i18n_env.get_template("pgettext.html")594 assert tmpl.render(LANGUAGE="de") == "Apple"595596 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"600601602class TestAutoEscape:603 def test_scoped_setting(self):604 env = Environment(autoescape=True)605 tmpl = env.from_string(
109 unmodified lines
modified:CHANGES.rst+2 added
44 unmodified lines
45 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`515253Version 2.11.354--------------
780 unmodified lines