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;
services.yml
No changes are needed — no translator specifics are needed (apart from including a listener as in the previous post)
MyListener.php
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); $catalogue->addCatalogue($customCatalogue); }
Test using the following;
// debug code to test; echo $translator->trans('messages.key1');