8000 [Translation] add how to create custom message formatter. by aitboudad · Pull Request #8284 · symfony/symfony-docs · GitHub
[go: up one dir, main page]

Skip to content

[Translation] add how to create custom message formatter. #8284

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 24, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions components/translation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,8 @@ The constructor of the ``Translator`` class needs one argument: The locale.
.. code-block:: php

use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\MessageSelector;

$translator = new Translator('fr_FR', new MessageSelector());
$translator = new Translator('fr_FR');

.. note::

Expand Down
55 changes: 55 additions & 0 deletions components/translation/custom_message_formatter.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
.. index::
single: Translation; Create Custom Message formatter

Create Custom Message Formatter
===============================

The default Message Formatter provide a simple and easy way that deals with the most common use-cases
such as message placeholders and pluralization. But in some cases, you may want to use a custom message formatter
that fit to your specific needs, for example, handle nested conditions of pluralization or select sub-messages
via a fixed set of keywords (e.g. gender).

Suppose in your application you want to displays different text depending on arbitrary conditions,
for example upon whether the guest is male or female. To do this, we will use the `ICU Message Format`_
which the most suitable ones you first need to create a `IntlMessageFormatter` and pass it to the `Translator`.

.. _components-translation-message-formatter:

Creating a Custom Message Formatter
-----------------------------------

To define a custom message formatter that is able to read these kinds of rules, you must create a
new class that implements the
:class:`Symfony\\Component\\Translation\\Formatter\\MessageFormatterInterface`::

use Symfony\Component\Translation\Formatter\MessageFormatterInterface;

class IntlMessageFormatter implements MessageFormatterInterface
{
public function format($message, $locale, array $parameters = array())
{
$formatter = new \MessageFormatter($locale, $message);
if (null === $formatter) {
throw new \InvalidArgumentException(sprintf('Invalid message format. Reason: %s (error #%d)', intl_get_error_message(), intl_get_error_code()));
}

$message = $formatter->format($parameters);
if ($formatter->getErrorCode() !== U_ZERO_ERROR) {
throw new \InvalidArgumentException(sprintf('Unable to format message. Reason: %s (error #%s)', $formatter->getErrorMessage(), $formatter->getErrorCode()));
}

return $message;
}
}

Once created, simply pass it as the second argument to the `Translator`::

use Symfony\Component\Translation\Translator;

$translator = new Translator('fr_FR', new IntlMessageFormatter());

var_dump($translator->trans('The guest is {gender, select, m {male} f {female}}', [ 'gender' => 'm' ]));

It will print *"The guest is male"*.

.. _`ICU Message Format`: http://userguide.icu-project.org/formatparse/messages
15 changes: 15 additions & 0 deletions reference/configuration/framework.rst
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ Configuration
* :ref:`enabled <reference-translator-enabled>`
* `fallbacks`_
* `logging`_
* `formatter`_
* :ref:`paths <reference-translator-paths>`
* `property_access`_
* `magic_call`_
Expand Down Expand Up @@ -1481,6 +1482,20 @@ for a given key. The logs are made to the ``translation`` channel and at the
``debug`` for level for keys where there is a translation in the fallback
locale and the ``warning`` level if there is no translation to use at all.

.. _reference-framework-translator-formatter:

formatter
.........

**type**: ``string`` **default**: ``translator.formatter.default``

The service that is used to format message. The service
has to implement the :class:`Symfony\\Component\\Translation\\Formatter\\MessageFormatterInterface`.

.. seealso::

For more details, see :doc:`/components/translation/custom_message_formatter`.

.. _reference-translator-paths:

paths
Expand Down
0