Skip to content
Myr

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

3 files+151 added−113 removed

modified:docs/extensions.rst+87 added-73 removed
25 unmodified lines
26--------------2728**Import name:** ``jinja2.ext.i18n``2930The i18n extension can be used in combination with `gettext`_ or `babel`_. If31the i18n extension is enabled Jinja2 provides a ``trans`` statement that marks32the wrapped string as translatable and calls ``gettext``.30The i18n extension can be used in combination with `gettext`_ or31`Babel`_. When it's enabled, Jinja provides a ``trans`` statement that32marks a block as translatable and calls ``gettext``.3334After enabling, dummy ``_`` function that forwards calls to ``gettext`` is added35to the environment globals. An internationalized application then has to36provide a ``gettext`` function and optionally an ``ngettext`` function into the37namespace, either globally or for each rendering.34After enabling, an application has to provide ``gettext`` and35``ngettext`` functions, either globally or when rendering. A ``_()``36function is added as an alias to the ``gettext`` function.3738Environment Methods39~~~~~~~~~~~~~~~~~~~40
1 unmodified line
42additional methods:4344.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)4547 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.5152 .. versionchanged:: 2.5 newstyle gettext added52 .. versionchanged:: 2.5 Added new-style gettext support.5354.. method:: jinja2.Environment.install_null_translations(newstyle=False)5556 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.5960 .. versionchanged:: 2.5 newstyle gettext added60 .. versionchanged:: 2.5 Added new-style gettext support.6162.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)6364 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).6869 If ``newstyle`` is activated, the callables are wrapped to work like70 newstyle callables. See :ref:`newstyle-gettext` for more information.7172 .. versionadded:: 2.572 .. versionadded:: 2.5 Added new-style gettext support.7374.. method:: jinja2.Environment.uninstall_gettext_translations()7576 Uninstall the translations again.76 Uninstall the environment's globally installed translation.7778.. method:: jinja2.Environment.extract_translations(source)7980 Extract localizable strings from the given template node or source.8182 For every string found this function yields a ``(lineno, function,83 message)`` tuple, where:8485 * ``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.9191 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.9494For a web application that is available in multiple languages but gives all95the users the same language (for example a multilingual forum software96installed for a French community) may load the translations once and add the97translation methods to the environment at environment generation time::95For a web application that is available in multiple languages but gives96all the users the same language (for example, multilingual forum97software installed for a French community), the translation may be98installed when the environment is created.99100.. code-block:: python101102 translations = get_gettext_translations()100 env = Environment(extensions=['jinja2.ext.i18n'])103 env = Environment(extensions=["jinja2.ext.i18n"])104 env.install_gettext_translations(translations)105103The ``get_gettext_translations`` function would return the translator for the104current configuration. (For example by using ``gettext.find``)106The ``get_gettext_translations`` function would return the translator107for the current configuration, for example by using ``gettext.find``.108106The usage of the ``i18n`` extension for template designers is covered as part107:ref:`of the template documentation <i18n-in-templates>`.109The usage of the ``i18n`` extension for template designers is covered in110:ref:`the template documentation <i18n-in-templates>`.111112.. _gettext: https://docs.python.org/3/library/gettext.html113.. _Babel: http://babel.pocoo.org/114112.. _newstyle-gettext:115116Whitespace Trimming117~~~~~~~~~~~~~~~~~~~118119.. versionadded:: 2.10120119Linebreaks and surrounding whitespace can be automatically trimmed by enabling120the ``ext.i18n.trimmed`` :ref:`policy <ext-i18n-trimmed>`.121Within ``{% trans %}`` blocks, it can be useful to trim line breaks and122whitespace so that the block of text looks like a simple string with123single spaces in the translation file.124125Linebreaks and surrounding whitespace can be automatically trimmed by126enabling the ``ext.i18n.trimmed`` :ref:`policy <ext-i18n-trimmed>`.127123Newstyle Gettext124~~~~~~~~~~~~~~~~128129.. _newstyle-gettext:130131New Style Gettext132~~~~~~~~~~~~~~~~~133134.. versionadded:: 2.5135128Starting with version 2.5 you can use newstyle gettext calls. These are129inspired by trac's internal gettext functions and are fully supported by130the babel extraction tool. They might not work as expected by other131extraction tools in case you are not using Babel's.136New style gettext calls are less to type, less error prone, and support137autoescaping better.138133What's the big difference between standard and newstyle gettext calls? In134general they are less to type and less error prone. Also if they are used135in an autoescaping environment they better support automatic escaping.136Here are some common differences between old and new calls:139You 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 Babel142extraction tool, but might not work as expected with other extraction143tools.144138standard gettext:145With standard ``gettext`` calls, string formatting is a separate step146done with the ``|format`` filter. This requires duplicating work for147``ngettext`` calls.148140.. sourcecode:: html+jinja149.. sourcecode:: jinja150142 {{ 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) }}156148newstyle gettext looks like this instead:157New style ``gettext`` make formatting part of the call, and behind the158scenes enforce more consistency.159150.. sourcecode:: html+jinja160.. sourcecode:: jinja161152 {{ 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) }}165156The advantages of newstyle gettext are that you have less to type and that157named placeholders become mandatory. The latter sounds like a158disadvantage but solves a lot of troubles translators are often facing159when they are unable to switch the positions of two placeholder. With160newstyle gettext, all format strings look the same.166The advantages of newstyle gettext are:167162Furthermore with newstyle gettext, string formatting is also used if no163placeholders are used which makes all strings behave exactly the same.164Last but not least are newstyle gettext calls able to properly mark165strings for autoescaping which solves lots of escaping related issues many166templates 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.180181182Expression Statement183--------------------184185**Import name:** ``jinja2.ext.do``
191 unmodified lines
modified:docs/templates.rst+59 added-39 removed
1567 unmodified lines
1568extensions not covered by this documentation; in which case there should1569be a separate document explaining said :ref:`extensions1570<jinja-extensions>`.157115721573.. _i18n-in-templates:15741575i18n1576~~~~15771577If the i18n extension is enabled, it's possible to mark parts in the template1578as translatable. To mark a section as translatable, you can use `trans`::1578If the :ref:`i18n-extension` is enabled, it's possible to mark text in1579the template as translatable. To mark a section as translatable, use a1580``trans`` block:15811580 <p>{% trans %}Hello {{ user }}!{% endtrans %}</p>1582.. code-block:: jinja15831582To translate a template expression --- say, using template filters, or by just1583accessing an attribute of an object --- you need to bind the expression to a1584name for use within the translation block::1584 {% trans %}Hello, {{ user }}!{% endtrans %}15851586 <p>{% trans user=user.username %}Hello {{ user }}!{% endtrans %}</p>1586Inside the block, no statements are allowed, only text and simple1587variable tags.15881588If you need to bind more than one expression inside a `trans` tag, separate1589the pieces with a comma (``,``)::1589Variable tags can only be a name, not attribute access, filters, or1590other expressions. To use an expression, bind it to a name in the1591``trans`` tag for use in the block.15921593.. code-block:: jinja15941595 {% trans user=user.username %}Hello, {{ user }}!{% endtrans %}15961597To bind more than one expression, separate each with a comma (``,``).15981599.. code-block:: jinja16001601 {% trans book_title=book.title, author=author.name %}1602 This is {{ book_title }} by {{ author }}1603 {% endtrans %}16041595Inside trans tags no statements are allowed, only variable tags are.1605To pluralize, specify both the singular and plural forms separated by1606the ``pluralize`` tag.16071597To pluralize, specify both the singular and plural forms with the `pluralize`1598tag, which appears between `trans` and `endtrans`::1608.. code-block:: jinja16091610 {% trans count=list|length %}1611 There is {{ count }} {{ name }} object.1612 {% pluralize %}1613 There are {{ count }} {{ name }} objects.1614 {% endtrans %}16151606By default, the first variable in a block is used to determine the correct1607singular or plural form. If that doesn't work out, you can specify the name1608which should be used for pluralizing by adding it as parameter to `pluralize`::1616By default, the first variable in a block is used to determine whether1617to use singular or plural form. If that isn't correct, specify the1618variable used for pluralizing as a parameter to ``pluralize``.16191620.. code-block:: jinja16211622 {% trans ..., user_count=users|length %}...1623 {% pluralize user_count %}...{% endtrans %}16241613When translating longer blocks of text, whitespace and linebreaks result in1614rather ugly and error-prone translation strings. To avoid this, a trans block1615can be marked as trimmed which will replace all linebreaks and the whitespace1616surrounding them with a single space and remove leading/trailing whitespace::1625When translating blocks of text, whitespace and linebreaks result in1626hard to read and error-prone translation strings. To avoid this, a trans1627block can be marked as trimmed, which will replace all linebreaks and1628the whitespace surrounding them with a single space and remove leading1629and trailing whitespace.16301631.. code-block:: jinja16321633 {% trans trimmed book_title=book.title %}1634 This is {{ book_title }}.1635 You should read it!1636 {% endtrans %}16371623If trimming is enabled globally, the `notrimmed` modifier can be used to1624disable it for a `trans` block.1638This results in ``This is %(book_title)s. You should read it!`` in the1639translation file.16401641If trimming is enabled globally, the ``notrimmed`` modifier can be used1642to disable it for a block.16431644.. versionadded:: 2.101627 The `trimmed` and `notrimmed` modifiers have been added.1645 The ``trimmed`` and ``notrimmed`` modifiers have been added.16461629It's also possible to translate strings in expressions. For that purpose,1630three functions exist:1647It's possible to translate strings in expressions with these functions:16481632- `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``16521636For example, you can easily print a translated string like this::1653You can print a translated string like this:16541638 {{ _('Hello World!') }}1655.. code-block:: jinja16561640To use placeholders, use the `format` filter::1657 {{ _("Hello, World!") }}16581642 {{ _('Hello %(user)s!')|format(user=user.username) }}1659To use placeholders, use the ``format`` filter.16601644For multiple placeholders, always use keyword arguments to `format`,1645as other languages may not use the words in the same order.1661.. code-block:: jinja16621647.. versionchanged:: 2.51663 {{ _("Hello, %(user)s!")|format(user=user.username) }}16641649If newstyle gettext calls are activated (:ref:`newstyle-gettext`), using1650placeholders is a lot easier:1665Always use keyword arguments to ``format``, as other languages may not1666use the words in the same order.16671652.. sourcecode:: html+jinja1668If :ref:`newstyle-gettext` calls are activated, using placeholders is1669easier. Formatting is part of the ``gettext`` call instead of using the1670``format`` filter.16711672.. sourcecode:: jinja16731674 {{ gettext('Hello World!') }}1675 {{ gettext('Hello %(name)s!', name='World') }}1676 {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}16771658Note that the `ngettext` function's format string automatically receives1659the count as a `num` parameter in addition to the regular parameters.1678The ``ngettext`` function's format string automatically receives the1679count as a ``num`` parameter in addition to the given parameters.168016811682Expression Statement1683~~~~~~~~~~~~~~~~~~~~
134 unmodified lines
modified:jinja2/ext.py+5 added-1 removed
146 unmodified lines
147 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 gettext156157
3 unmodified lines
161 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 ngettext168169170class InternationalizationExtension(Extension):171 """This extension adds gettext support to Jinja2."""168 tags = set(['trans'])172 tags = {'trans'}173174 # TODO: the i18n extension is currently reevaluating values in a few175 # situations. Take this example:176 # {% trans count=something() %}{{ count }} foo{% pluralize
506 unmodified lines