How to generate symfony2 translations inside controller?

巧了我就是萌 提交于 2019-12-10 15:57:38

问题


Symfony2 project. I'm using JMSTranslationsBundle.

Here is a fragment from function inside controller:

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

How to generate translation for 'user.account.confirmed' in .xliff file? I mean, what code I should add to this function to be able to translate it?


回答1:


Looking at the available extraction methods, it explains that there is no automatic extraction for your case available.

You will need to use 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 in one my projects.

With that you simply define a new method in your controller, which returns the "to-be-translated" strings:

<?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')
        ];
    }
}

An alternate solution would be to directly use the translater service. The call to this service should then again be visible to the extractor. E.g:

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

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


来源:https://stackoverflow.com/questions/33540385/how-to-generate-symfony2-translations-inside-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!