4

我正在尝试在 symfony2 (2.3.0) 控制台命令中使用翻译器,但我无法使其工作。这是我到目前为止所做的:

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存在于messages.yml 中。知道如何使它工作吗?

谢谢!

4

1 回答 1

8

我刚刚发现在 symfony2 控制台命令中,config.yml从未使用过定义的默认语言环境,因此语言环境是NULL. 所以翻译者永远不会使用任何可用的翻译语言环境。这就是为什么原封不动地返回翻译键而不是翻译的原因。

当我只运行试图翻译某些内容的控制台命令时,我得到了这个提示,但没有生成 app/cache/dev/translations 文件夹中的目录。

所以,这就是我在控制台命令中进行翻译的方法(在我的例子中,我将它设置为 id_ID):

$translator = $this->getContainer()->get('translator');
$translator->setLocale("id_ID");

echo $translator->trans('my.translation.key'); // works fine! :)

希望这可以帮助任何面临同样问题的人。:)

于 2013-08-23T07:00:51.020 回答