如何在控制器内生成 symfony2 翻译?

How to generate symfony2 translations inside controller?

Symfony2 项目。我正在使用 JMSTranslationsBundle。

这是控制器内部函数的片段:

if ($user->isAccountConfirmed()) {
            $this->toolbar->addInfo('user.account.confirmed');
        }

如何在 .xliff 文件中为 'user.account.confirmed' 生成翻译?我的意思是,我应该向这个函数添加什么代码才能翻译它?

查看 available extraction methods,它解释说您的案例没有可用的自动提取。

您将需要在我的一个项目中使用 trans (or any of the other methods explained) in your template or in the controller. Without this hint, the extractor will not be able to find your message. Personally I have used TranslationContainerInterface

有了它,您只需在控制器中定义一个新方法,returns "to-be-translated" 字符串:

<?php
// ...
use JMS\TranslationBundle\Translation\TranslationContainerInterface;
use JMS\TranslationBundle\Model\Message;

class AcmeController extends Controller implements TranslationContainerInterface
{
    /**
     * {@inheritdoc}
     */
    static function getTranslationMessages()
    {
        return [
            Message::create('user.account.confirmed')
        ];
    }
}

另一种解决方案是直接使用 translater service。对该服务的调用应该再次对提取器可见。例如:

/** @var $translator \Symfony\Component\Translation\TranslatorInterface */
$translator = $this->get('translator');

if ($user->isAccountConfirmed()) {
    $this->toolbar->addInfo(
        $translator->trans('user.account.confirmed')
    );
}