specify context for translation block
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 896a621 · Browse files · 4 files·+63 added−19 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+63 added−19 removed
- tests:+13 added−1 removed
- other:+50 added−18 removed
Provenance
- Commit
b6f50df- Tree
9cef366- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
896a621
4 files changed+63 added−19 removed
modified:docs/templates.rst+27 added-3 removed
1730 unmodified lines1731 1732 .. versionadded:: 2.101733 The ``trimmed`` and ``notrimmed`` modifiers have been added.1734 1735+If the translation depends on the context that the message appears in,1736+the ``pgettext`` and ``npgettext`` functions take a ``context`` string1737+as the first argument, which is used to select the appropriate1738+translation. To specify a context with the ``{% trans %}`` tag, provide1739+a string as the first token after ``trans``.1740+1741+.. code-block:: jinja1742+1743+ {% trans "fruit" %}apple{% endtrans %}1744+ {% trans "fruit" trimmed count -%}1745+ 1 apple1746+ {%- pluralize -%}1747+ {{ count }} apples1748+ {%- endtrans %}1749+1750+.. versionadded:: 3.11751+ A context can be passed to the ``trans`` tag to use ``pgettext`` and1752+ ``npgettext``.1753+1754 It's possible to translate strings in expressions with these functions:1755 1737-- ``gettext``: translate a single string1738-- ``ngettext``: translate a pluralizable string1739-- ``_``: alias for ``gettext``1756+- ``_(message)``: Alias for ``gettext``.1757+- ``gettext(message)``: Translate a message.1758+- ``ngettext(singluar, plural, n)``: Translate a singular or plural1759+ message based on a count variable.1760+- ``pgettext(context, message)``: Like ``gettext()``, but picks the1761+ translation based on the context string.1762+- ``npgettext(context, singular, plural, n)``: Like ``npgettext()``,1763+ but picks the translation based on the context string.1764 1765 You can print a translated string like this:1766 1767 .. code-block:: jinja162 unmodified linesmodified:src/jinja2/ext.py+20 added-15 removed
352 unmodified lines353 354 def parse(self, parser: "Parser") -> t.Union[nodes.Node, t.List[nodes.Node]]:355 """Parse a translatable tag."""356 lineno = next(parser.stream).lineno357- num_called_num = False357 358+ context = None359+ context_token = parser.stream.next_if("string")360+361+ if context_token is not None:362+ context = context_token.value363+364 # find all the variables referenced. Additionally a variable can be365 # defined in the body of the trans block too, but this is checked at366 # a later state.367 plural_expr: t.Optional[nodes.Expr] = None368 plural_expr_assignment: t.Optional[nodes.Assign] = None369+ num_called_num = False370 variables: t.Dict[str, nodes.Expr] = {}371 trimmed = None372 while parser.stream.current.type != "block_end":373 if variables:86 unmodified lines460 461 node = self._make_node(462 singular,463 plural,464+ context,465 variables,466 plural_expr,467 bool(referenced),468 num_called_num and have_plural,47 unmodified lines516 def _make_node(517 self,518 singular: str,519 plural: t.Optional[str],520+ context: t.Optional[str],521 variables: t.Dict[str, nodes.Expr],522 plural_expr: t.Optional[nodes.Expr],523 vars_referenced: bool,524 num_called_num: bool,8 unmodified lines533 singular = singular.replace("%%", "%")534 if plural:535 plural = plural.replace("%%", "%")536 529- # singular only:530- if plural_expr is None:531- gettext = nodes.Name("gettext", "load")532- node = nodes.Call(gettext, [nodes.Const(singular)], [], None, None)537+ func_name = "gettext"538+ func_args: t.List[nodes.Expr] = [nodes.Const(singular)]539 534- # singular and plural535- else:536- ngettext = nodes.Name("ngettext", "load")537- node = nodes.Call(538- ngettext,539- [nodes.Const(singular), nodes.Const(plural), plural_expr],540- [],541- None,542- None,543- )540+ if context is not None:541+ func_args.insert(0, nodes.Const(context))542+ func_name = f"p{func_name}"543 544+ if plural_expr is not None:545+ func_name = f"n{func_name}"546+ func_args.extend((nodes.Const(plural), plural_expr))547+548+ node = nodes.Call(nodes.Name(func_name, "load"), func_args, [], None, None)549+550 # in case newstyle gettext is used, the method is powerful551 # enough to handle the variable expansion and autoescape552 # handling itself553 if newstyle:306 unmodified linesmodified:tests/test_ext.py+13 added-1 removed
41 unmodified lines42 "{{ num }} apples{% endtrans %}",43 "pgettext.html": '{{ pgettext("fruit", "Apple") }}',44 "npgettext.html": '{{ npgettext("fruit", "%(num)s apple", "%(num)s apples",'45 " apples) }}",46+ "pgettext_block": "{% trans 'fruit' num=apples %}Apple{% endtrans %}",47+ "npgettext_block": "{% trans 'fruit' num=apples %}{{ num }} apple"48+ "{% pluralize %}{{ num }} apples{% endtrans %}",49 "transvars1.html": "{% trans %}User: {{ num }}{% endtrans %}",50 "transvars2.html": "{% trans num=count %}User: {{ num }}{% endtrans %}",51 "transvars3.html": "{% trans count=num %}User: {{ count }}{% endtrans %}",52 "novars.html": "{% trans %}%(hello)s{% endtrans %}",542 unmodified lines595 def test_context(self):596 tmpl = newstyle_i18n_env.get_template("pgettext.html")597 assert tmpl.render(LANGUAGE="de") == "Apple"598 596- def test_context_newstyle_plural(self):599+ def test_context_plural(self):600 tmpl = newstyle_i18n_env.get_template("npgettext.html")601 assert tmpl.render(LANGUAGE="de", apples=1) == "1 Apple"602 assert tmpl.render(LANGUAGE="de", apples=5) == "5 Apples"603 604+ def test_context_block(self):605+ tmpl = newstyle_i18n_env.get_template("pgettext_block")606+ assert tmpl.render(LANGUAGE="de") == "Apple"607 608+ def test_context_plural_block(self):609+ tmpl = newstyle_i18n_env.get_template("npgettext_block")610+ assert tmpl.render(LANGUAGE="de", apples=1) == "1 Apple"611+ assert tmpl.render(LANGUAGE="de", apples=5) == "5 Apples"612+613+614 class TestAutoEscape:615 def test_scoped_setting(self):616 env = Environment(autoescape=True)617 tmpl = env.from_string(109 unmodified linesmodified:CHANGES.rst+3 added
21 unmodified lines22 ``resolve``.23 - ``unicode_urlencode`` is renamed to ``url_quote``.24 25 - Add support for native types in macros. :issue:`1510`26+- The ``{% trans %}`` tag can use ``pgettext`` and ``npgettext`` by27+ passing a context string as the first token in the tag, like28+ ``{% trans "title" %}``. :issue:`1430`29 30 31 Version 3.0.332 -------------911 unmodified lines