|
| 1 | +.. index:: |
| 2 | + single: Translation; Create Custom Message formatter |
| 3 | + |
| 4 | +Create a Custom Message Formatter |
| 5 | +================================= |
| 6 | + |
| 7 | +The default message formatter provided by Symfony solves the most common needs |
| 8 | +when translating messages, such as using variables and pluralization. However, |
| 9 | +if your needs are different, you can create your own message formatter. |
| 10 | + |
| 11 | +Message formatters are PHP classes that implement the |
| 12 | +:class:`Symfony\\Component\\Translation\\Formatter\\MessageFormatterInterface`:: |
| 13 | + |
| 14 | + |
| 15 | + use Symfony\Component\Translation\Formatter\MessageFormatterInterface; |
| 16 | + |
| 17 | + class MyCustomMessageFormatter implements MessageFormatterInterface |
| 18 | + { |
| 19 | + public function format($message, $locale, array $parameters = []) |
| 20 | + { |
| 21 | + // ... format the message according to your needs |
| 22 | + |
| 23 | + return $message; |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | +Now, pass an instance of this formatter as the second argument of the translator |
| 28 | +to use it when translating messages:: |
| 29 | + |
| 30 | + use Symfony\Component\Translation\Translator; |
| 31 | + |
| 32 | + $translator = new Translator('fr_FR', new IntlMessageFormatter()); |
| 33 | + $message = $translator->trans($originalMessage, $translationParameters); |
| 34 | + |
| 35 | +If you want to use this formatter to translate all messages in your Symfony |
| 36 | +application, define a service for the formatter and use the |
| 37 | +:ref:`translator.formatter <reference-framework-translator-formatter>` option |
| 38 | +to set that service as the default formatter. |
0 commit comments