Symfony2: how to use a translator in the command console

I am trying to use the translator in the symfony2 (2.3.0) command, but I cannot get it to work. Here is what I have done so far:

use Symfony\Component\Translation\IdentityTranslator; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class SendMessageCommand extends ContainerAwareCommand { protected function configure() { $this->setName('mycommand:sendmessage')->setDescription('send message.'); } protected function execute(InputInterface $input, OutputInterface $output) { $translator = $this->getContainer()->get('translator'); echo $translator->trans('my.translation.key'); // not working } } 

my.translation.key exists in messages.yml. Any idea how to make it work?

thanks!

+4
source share
1 answer

I just found that in the symfony2 console command, the default locale defined in config.yml is never used, so the locale is NULL . Therefore, the translator will never use the language version of the translation. This is why the translation key is returned intact instead of the translation.

I got this advice when I run only a console command that tries to translate something, but the directory in the app / cache / dev / translations folder is not generated.

So, this is how I do it to make translations in console commands (in my case, I set its id_ID):

 $translator = $this->getContainer()->get('translator'); $translator->setLocale("id_ID"); echo $translator->trans('my.translation.key'); // works fine! :) 

Hope this helps anyone facing the same problem. :)

+8
source

Source: https://habr.com/ru/post/1498125/


All Articles