English spoken conference

Symfony 5: The Fast Track

A new book to learn about developing modern Symfony 5 applications.

Support this project

You are browsing the Symfony 4.3 documentation, which changes significantly from Symfony 3.x. If your app doesn't use Symfony 4.3 yet, browse the Symfony 3.4 documentation.

Create a Custom Message Formatter

Create a Custom Message FormatterΒΆ

The default message formatter provided by Symfony solves the most common needs when translating messages, such as using variables and pluralization. However, if your needs are different, you can create your own message formatter.

Message formatters are PHP classes that implement the MessageFormatterInterface:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
use Symfony\Component\Translation\Formatter\MessageFormatterInterface;

class MyCustomMessageFormatter implements MessageFormatterInterface
{
    public function format($message, $locale, array $parameters = [])
    {
        // ... format the message according to your needs

        return $message;
    }
}

Now, pass an instance of this formatter as the second argument of the translator to use it when translating messages:

use Symfony\Component\Translation\Translator;

$translator = new Translator('fr_FR', new IntlMessageFormatter());
$message = $translator->trans($originalMessage, $translationParameters);

If you want to use this formatter to translate all messages in your Symfony application, define a service for the formatter and use the translator.formatter option to set that service as the default formatter.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.