Symfony: Adding messages to the translator dynamically (updated)

This is an update to the previous translator post, allowing the system to use the default translator and just adding the required messages to the message-catalogue in-use.

This is a better approach as it doesn’t then mean you miss out on the good things Symfony provides out-of-the-box because you’ve had to define what specific component is in use for the translator.

Anyway — code is below;

No changes are needed — no translator specifics are needed (apart from including a listener as in the previous post)


Add a function to your kernel.event-listener as below;

 * @param TranslatorInterface $translator
public function addTranslatorResources(TranslatorInterface $translator) {
   $locale = $translator->getLocale();
   $catalogue = $translator->getCatalogue($locale);
   $translations = ['messages' => ['key1' => 'my message is here']];
   $loader = new ArrayLoader();
   $customCatalogue = $loader->load($translations, $locale);

Test using the following;

// debug code to test;
 echo $translator->trans('messages.key1');

Symfony: Adding to the translator dynamically

Leave a Reply