Merge pull request #1084 from pallets/i18n-docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
clean up i18n documentation
authored by David Lord · committed by GitHub · parents 91893a4, 50f1810 · Browse files · 3 files·+151 added−113 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+151 added−113 removed
- other:+151 added−113 removed
Provenance
- Commit
1b3d6ed- Tree
02bab39- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
91893a4- Parent 2
50f1810
3 files changed+151 added−113 removed
modified:docs/extensions.rst+87 added-73 removed
25 unmodified lines26 --------------27 28 **Import name:** ``jinja2.ext.i18n``29 30-The i18n extension can be used in combination with `gettext`_ or `babel`_. If31-the i18n extension is enabled Jinja2 provides a ``trans`` statement that marks32-the wrapped string as translatable and calls ``gettext``.30+The i18n extension can be used in combination with `gettext`_ or31+`Babel`_. When it's enabled, Jinja provides a ``trans`` statement that32+marks a block as translatable and calls ``gettext``.33 34-After enabling, dummy ``_`` function that forwards calls to ``gettext`` is added35-to the environment globals. An internationalized application then has to36-provide a ``gettext`` function and optionally an ``ngettext`` function into the37-namespace, either globally or for each rendering.34+After enabling, an application has to provide ``gettext`` and35+``ngettext`` functions, either globally or when rendering. A ``_()``36+function is added as an alias to the ``gettext`` function.37 38 Environment Methods39 ~~~~~~~~~~~~~~~~~~~40 1 unmodified line42 additional methods:43 44 .. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)45 47- Installs a translation globally for that environment. The translations48- object provided must implement at least ``ugettext`` and ``ungettext``.49- The ``gettext.NullTranslations`` and ``gettext.GNUTranslations`` classes50- as well as `Babel`_\s ``Translations`` class are supported.46+ Installs a translation globally for the environment. The47+ ``translations`` object must implement ``gettext`` and ``ngettext``48+ (or ``ugettext`` and ``ungettext`` for Python 2).49+ :class:`gettext.NullTranslations`, :class:`gettext.GNUTranslations`,50+ and `Babel`_\s ``Translations`` are supported.51 52- .. versionchanged:: 2.5 newstyle gettext added52+ .. versionchanged:: 2.5 Added new-style gettext support.53 54 .. method:: jinja2.Environment.install_null_translations(newstyle=False)55 56- Install dummy gettext functions. This is useful if you want to prepare57- the application for internationalization but don't want to implement the58- full internationalization system yet.56+ Install no-op gettext functions. This is useful if you want to57+ prepare the application for internationalization but don't want to58+ implement the full system yet.59 60- .. versionchanged:: 2.5 newstyle gettext added60+ .. versionchanged:: 2.5 Added new-style gettext support.61 62 .. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)63 64- Installs the given ``gettext`` and ``ngettext`` callables into the65- environment as globals. They are supposed to behave exactly like the66- standard library's :func:`gettext.ugettext` and67- :func:`gettext.ungettext` functions.64+ Install the given ``gettext`` and ``ngettext`` callables into the65+ environment. They should behave exactly like66+ :func:`gettext.gettext` and :func:`gettext.ngettext` (or67+ ``ugettext`` and ``ungettext`` for Python 2).68 69 If ``newstyle`` is activated, the callables are wrapped to work like70 newstyle callables. See :ref:`newstyle-gettext` for more information.71 72- .. versionadded:: 2.572+ .. versionadded:: 2.5 Added new-style gettext support.73 74 .. method:: jinja2.Environment.uninstall_gettext_translations()75 76- Uninstall the translations again.76+ Uninstall the environment's globally installed translation.77 78 .. method:: jinja2.Environment.extract_translations(source)79 80 Extract localizable strings from the given template node or source.81 82 For every string found this function yields a ``(lineno, function,83 message)`` tuple, where:84 85- * ``lineno`` is the number of the line on which the string was found,86- * ``function`` is the name of the ``gettext`` function used (if the87- string was extracted from embedded Python code), and88- * ``message`` is the string itself (a ``unicode`` object, or a tuple89- of ``unicode`` objects for functions with multiple string arguments).85+ - ``lineno`` is the number of the line on which the string was86+ found.87+ - ``function`` is the name of the ``gettext`` function used (if88+ the string was extracted from embedded Python code).89+ - ``message`` is the string itself (``unicode`` on Python 2), or a90+ tuple of strings for functions with multiple arguments.91 91- If `Babel`_ is installed, :ref:`the babel integration <babel-integration>`92- can be used to extract strings for babel.92+ If `Babel`_ is installed, see :ref:`babel-integration` to extract93+ the strings.94 94-For a web application that is available in multiple languages but gives all95-the users the same language (for example a multilingual forum software96-installed for a French community) may load the translations once and add the97-translation methods to the environment at environment generation time::95+For a web application that is available in multiple languages but gives96+all the users the same language (for example, multilingual forum97+software installed for a French community), the translation may be98+installed when the environment is created.99 100+.. code-block:: python101+102 translations = get_gettext_translations()100- env = Environment(extensions=['jinja2.ext.i18n'])103+ env = Environment(extensions=["jinja2.ext.i18n"])104 env.install_gettext_translations(translations)105 103-The ``get_gettext_translations`` function would return the translator for the104-current configuration. (For example by using ``gettext.find``)106+The ``get_gettext_translations`` function would return the translator107+for the current configuration, for example by using ``gettext.find``.108 106-The usage of the ``i18n`` extension for template designers is covered as part107-:ref:`of the template documentation <i18n-in-templates>`.109+The usage of the ``i18n`` extension for template designers is covered in110+:ref:`the template documentation <i18n-in-templates>`.111 112 .. _gettext: https://docs.python.org/3/library/gettext.html113 .. _Babel: http://babel.pocoo.org/114 112-.. _newstyle-gettext:115 116 Whitespace Trimming117 ~~~~~~~~~~~~~~~~~~~118 119 .. versionadded:: 2.10120 119-Linebreaks and surrounding whitespace can be automatically trimmed by enabling120-the ``ext.i18n.trimmed`` :ref:`policy <ext-i18n-trimmed>`.121+Within ``{% trans %}`` blocks, it can be useful to trim line breaks and122+whitespace so that the block of text looks like a simple string with123+single spaces in the translation file.124 125+Linebreaks and surrounding whitespace can be automatically trimmed by126+enabling the ``ext.i18n.trimmed`` :ref:`policy <ext-i18n-trimmed>`.127 123-Newstyle Gettext124-~~~~~~~~~~~~~~~~128 129+.. _newstyle-gettext:130+131+New Style Gettext132+~~~~~~~~~~~~~~~~~133+134 .. versionadded:: 2.5135 128-Starting with version 2.5 you can use newstyle gettext calls. These are129-inspired by trac's internal gettext functions and are fully supported by130-the babel extraction tool. They might not work as expected by other131-extraction tools in case you are not using Babel's.136+New style gettext calls are less to type, less error prone, and support137+autoescaping better.138 133-What's the big difference between standard and newstyle gettext calls? In134-general they are less to type and less error prone. Also if they are used135-in an autoescaping environment they better support automatic escaping.136-Here are some common differences between old and new calls:139+You can use "new style" gettext calls by setting140+``env.newstyle_gettext = True`` or passing ``newstyle=True`` to141+``env.install_translations``. They are fully supported by the Babel142+extraction tool, but might not work as expected with other extraction143+tools.144 138-standard gettext:145+With standard ``gettext`` calls, string formatting is a separate step146+done with the ``|format`` filter. This requires duplicating work for147+``ngettext`` calls.148 140-.. sourcecode:: html+jinja149+.. sourcecode:: jinja150 142- {{ gettext('Hello World!') }}143- {{ gettext('Hello %(name)s!')|format(name='World') }}144- {{ ngettext('%(num)d apple', '%(num)d apples', apples|count)|format(145- num=apples|count146- )}}151+ {{ gettext("Hello, World!") }}152+ {{ gettext("Hello, %(name)s!")|format(name=name) }}153+ {{ ngettext(154+ "%(num)d apple", "%(num)d apples", apples|count155+ )|format(num=apples|count) }}156 148-newstyle gettext looks like this instead:157+New style ``gettext`` make formatting part of the call, and behind the158+scenes enforce more consistency.159 150-.. sourcecode:: html+jinja160+.. sourcecode:: jinja161 152- {{ gettext('Hello World!') }}153- {{ gettext('Hello %(name)s!', name='World') }}154- {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}162+ {{ gettext("Hello, World!") }}163+ {{ gettext("Hello, %(name)s!", name=name) }}164+ {{ ngettext("%(num)d apple", "%(num)d apples", apples|count) }}165 156-The advantages of newstyle gettext are that you have less to type and that157-named placeholders become mandatory. The latter sounds like a158-disadvantage but solves a lot of troubles translators are often facing159-when they are unable to switch the positions of two placeholder. With160-newstyle gettext, all format strings look the same.166+The advantages of newstyle gettext are:167 162-Furthermore with newstyle gettext, string formatting is also used if no163-placeholders are used which makes all strings behave exactly the same.164-Last but not least are newstyle gettext calls able to properly mark165-strings for autoescaping which solves lots of escaping related issues many166-templates are experiencing over time when using autoescaping.168+- There's no separate formatting step, you don't have to remember to169+ use the ``|format`` filter.170+- Only named placeholders are allowed. This solves a common problem171+ translators face because positional placeholders can't switch172+ positions meaningfully. Named placeholders always carry semantic173+ information about what value goes where.174+- String formatting is used even if no placeholders are used, which175+ makes all strings use a consistent format. Remember to escape any176+ raw percent signs as ``%%``, such as ``100%%``.177+- The translated string is marked safe, formatting performs escaping178+ as needed. Mark a parameter as ``|safe`` if it has already been179+ escaped.180 181+182 Expression Statement183 --------------------184 185 **Import name:** ``jinja2.ext.do``191 unmodified linesmodified:docs/templates.rst+59 added-39 removed
1567 unmodified lines1568 extensions not covered by this documentation; in which case there should1569 be a separate document explaining said :ref:`extensions1570 <jinja-extensions>`.1571 1572+1573 .. _i18n-in-templates:1574 1575 i18n1576 ~~~~1577 1577-If the i18n extension is enabled, it's possible to mark parts in the template1578-as translatable. To mark a section as translatable, you can use `trans`::1578+If the :ref:`i18n-extension` is enabled, it's possible to mark text in1579+the template as translatable. To mark a section as translatable, use a1580+``trans`` block:1581 1580- <p>{% trans %}Hello {{ user }}!{% endtrans %}</p>1582+.. code-block:: jinja1583 1582-To translate a template expression --- say, using template filters, or by just1583-accessing an attribute of an object --- you need to bind the expression to a1584-name for use within the translation block::1584+ {% trans %}Hello, {{ user }}!{% endtrans %}1585 1586- <p>{% trans user=user.username %}Hello {{ user }}!{% endtrans %}</p>1586+Inside the block, no statements are allowed, only text and simple1587+variable tags.1588 1588-If you need to bind more than one expression inside a `trans` tag, separate1589-the pieces with a comma (``,``)::1589+Variable tags can only be a name, not attribute access, filters, or1590+other expressions. To use an expression, bind it to a name in the1591+``trans`` tag for use in the block.1592 1593+.. code-block:: jinja1594+1595+ {% trans user=user.username %}Hello, {{ user }}!{% endtrans %}1596+1597+To bind more than one expression, separate each with a comma (``,``).1598+1599+.. code-block:: jinja1600+1601 {% trans book_title=book.title, author=author.name %}1602 This is {{ book_title }} by {{ author }}1603 {% endtrans %}1604 1595-Inside trans tags no statements are allowed, only variable tags are.1605+To pluralize, specify both the singular and plural forms separated by1606+the ``pluralize`` tag.1607 1597-To pluralize, specify both the singular and plural forms with the `pluralize`1598-tag, which appears between `trans` and `endtrans`::1608+.. code-block:: jinja1609 1610 {% trans count=list|length %}1611 There is {{ count }} {{ name }} object.1612 {% pluralize %}1613 There are {{ count }} {{ name }} objects.1614 {% endtrans %}1615 1606-By default, the first variable in a block is used to determine the correct1607-singular or plural form. If that doesn't work out, you can specify the name1608-which should be used for pluralizing by adding it as parameter to `pluralize`::1616+By default, the first variable in a block is used to determine whether1617+to use singular or plural form. If that isn't correct, specify the1618+variable used for pluralizing as a parameter to ``pluralize``.1619 1620+.. code-block:: jinja1621+1622 {% trans ..., user_count=users|length %}...1623 {% pluralize user_count %}...{% endtrans %}1624 1613-When translating longer blocks of text, whitespace and linebreaks result in1614-rather ugly and error-prone translation strings. To avoid this, a trans block1615-can be marked as trimmed which will replace all linebreaks and the whitespace1616-surrounding them with a single space and remove leading/trailing whitespace::1625+When translating blocks of text, whitespace and linebreaks result in1626+hard to read and error-prone translation strings. To avoid this, a trans1627+block can be marked as trimmed, which will replace all linebreaks and1628+the whitespace surrounding them with a single space and remove leading1629+and trailing whitespace.1630 1631+.. code-block:: jinja1632+1633 {% trans trimmed book_title=book.title %}1634 This is {{ book_title }}.1635 You should read it!1636 {% endtrans %}1637 1623-If trimming is enabled globally, the `notrimmed` modifier can be used to1624-disable it for a `trans` block.1638+This results in ``This is %(book_title)s. You should read it!`` in the1639+translation file.1640 1641+If trimming is enabled globally, the ``notrimmed`` modifier can be used1642+to disable it for a block.1643+1644 .. versionadded:: 2.101627- The `trimmed` and `notrimmed` modifiers have been added.1645+ The ``trimmed`` and ``notrimmed`` modifiers have been added.1646 1629-It's also possible to translate strings in expressions. For that purpose,1630-three functions exist:1647+It's possible to translate strings in expressions with these functions:1648 1632-- `gettext`: translate a single string1633-- `ngettext`: translate a pluralizable string1634-- `_`: alias for `gettext`1649+- ``gettext``: translate a single string1650+- ``ngettext``: translate a pluralizable string1651+- ``_``: alias for ``gettext``1652 1636-For example, you can easily print a translated string like this::1653+You can print a translated string like this:1654 1638- {{ _('Hello World!') }}1655+.. code-block:: jinja1656 1640-To use placeholders, use the `format` filter::1657+ {{ _("Hello, World!") }}1658 1642- {{ _('Hello %(user)s!')|format(user=user.username) }}1659+To use placeholders, use the ``format`` filter.1660 1644-For multiple placeholders, always use keyword arguments to `format`,1645-as other languages may not use the words in the same order.1661+.. code-block:: jinja1662 1647-.. versionchanged:: 2.51663+ {{ _("Hello, %(user)s!")|format(user=user.username) }}1664 1649-If newstyle gettext calls are activated (:ref:`newstyle-gettext`), using1650-placeholders is a lot easier:1665+Always use keyword arguments to ``format``, as other languages may not1666+use the words in the same order.1667 1652-.. sourcecode:: html+jinja1668+If :ref:`newstyle-gettext` calls are activated, using placeholders is1669+easier. Formatting is part of the ``gettext`` call instead of using the1670+``format`` filter.1671 1672+.. sourcecode:: jinja1673+1674 {{ gettext('Hello World!') }}1675 {{ gettext('Hello %(name)s!', name='World') }}1676 {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}1677 1658-Note that the `ngettext` function's format string automatically receives1659-the count as a `num` parameter in addition to the regular parameters.1678+The ``ngettext`` function's format string automatically receives the1679+count as a ``num`` parameter in addition to the given parameters.1680 1681 1682 Expression Statement1683 ~~~~~~~~~~~~~~~~~~~~134 unmodified linesmodified:jinja2/ext.py+5 added-1 removed
146 unmodified lines147 def gettext(__context, __string, **variables):148 rv = __context.call(func, __string)149 if __context.eval_ctx.autoescape:150 rv = Markup(rv)151+ # Always treat as a format string, even if there are no152+ # variables. This makes translation strings more consistent153+ # and predictable. This requires escaping154 return rv % variables155 return gettext156 157 3 unmodified lines161 variables.setdefault('num', __num)162 rv = __context.call(func, __singular, __plural, __num)163 if __context.eval_ctx.autoescape:164 rv = Markup(rv)165+ # Always treat as a format string, see gettext comment above.166 return rv % variables167 return ngettext168 169 170 class InternationalizationExtension(Extension):171 """This extension adds gettext support to Jinja2."""168- tags = set(['trans'])172+ tags = {'trans'}173 174 # TODO: the i18n extension is currently reevaluating values in a few175 # situations. Take this example:176 # {% trans count=something() %}{{ count }} foo{% pluralize506 unmodified lines