|
| 1 | +.. index:: |
| 2 | + single: Translation; Create Custom Message formatter |
| 3 | + |
| 4 | +Create Custom Message Formatter |
| 5 | +=============================== |
| 6 | + |
| 7 | +The default Message Formatter provide a simple and easy way that deals with the most common use-cases |
| 8 | +such as message placeholders and pluralization. But in some cases, you may want to use a custom message formatter |
| 9 | +that fit to your specific needs, for example, handle nested conditions of pluralization or select sub-messages |
| 10 | +via a fixed set of keywords (e.g. gender). |
| 11 | + |
| 12 | +Suppose in your application you want to displays different text depending on arbitrary conditions, |
| 13 | +for example upon whether the guest is male or female. To do this, we will use the `ICU Message Format`_ |
| 14 | +which the most suitable ones you first need to create a `IntlMessageFormatter` and pass it to the `Translator`. |
| 15 | + |
| 16 | +.. _components-translation-message-formatter: |
| 17 | + |
| 18 | +Creating a Custom Message Formatter |
| 19 | +----------------------------------- |
| 20 | + |
| 21 | +To define a custom message formatter that is able to read these kinds of rules, you must create a |
| 22 | +new class that implements the |
| 23 | +:class:`Symfony\\Component\\Translation\\Formatter\\MessageFormatterInterface`:: |
| 24 | + |
| 25 | + use Symfony\Component\Translation\Formatter\MessageFormatterInterface; |
| 26 | + |
| 27 | + class IntlMessageFormatter implements MessageFormatterInterface |
| 28 | + { |
| 29 | + public function format($message, $locale, array $parameters = array()) |
| 30 | + { |
| 31 | + $formatter = new \MessageFormatter($locale, $message); |
| 32 | + if (null === $formatter) { |
| 33 | + throw new \InvalidArgumentException(sprintf('Invalid message format. Reason: %s (error #%d)', intl_get_error_message(), intl_get_error_code())); |
| 34 | + } |
| 35 | + |
| 36 | + $message = $formatter->format($parameters); |
| 37 | + if ($formatter->getErrorCode() !== U_ZERO_ERROR) { |
| 38 | + throw new \InvalidArgumentException(sprintf('Unable to format message. Reason: %s (error #%s)', $formatter->getErrorMessage(), $formatter->getErrorCode())); |
| 39 | + } |
| 40 | + |
| 41 | + return $message; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | +Once created, simply pass it as the second argument to the `Translator`:: |
| 46 | + |
| 47 | + use Symfony\Component\Translation\Translator; |
| 48 | + |
| 49 | + $translator = new Translator('fr_FR', new IntlMessageFormatter()); |
| 50 | + |
| 51 | + var_dump($translator->trans('The guest is {gender, select, m {male} f {female}}', [ 'gender' => 'm' ])); |
| 52 | + |
| 53 | +It will print *"The guest is male"*. |
| 54 | + |
| 55 | +.. _`ICU Message Format`: http://userguide.icu-project.org/formatparse/messages |
0 commit comments