我今天遇到了翻译symfony的问题。
由SwiftMailer发送,电子邮件是在个人服务中创建的。
案例1:函数sendWelcomeEmailMessage在Controller中调用,只是在注册新用户时,trans键'registration.email.welcome.subject'翻译得很好
案例2:函数sendReflationEmailMessage在symfony2命令中被调用,但是在这里,键'registration.email.welcome.subject'(测试的相同键)没有被翻译...
有人有想法吗?
/**
* @param UserInterface $user
*/
public function sendWelcomeEmailMessage(UserInterface $user)
{
$params = $this->parameters['registration']['welcome'];
$rendered = $this->templating->render(
$params['template'], [
'user' => $user
]
);
$subject = $this->translator->trans('registration.email.welcome.subject');
$this->sendEmailMessage($rendered, $subject, $params['from_email'], $user->getEmail());
}
/**
* @param UserInterface $user
*/
public function sendReflationEmailMessage(UserInterface $user)
{
$params = $this->parameters['registration']['reflation'];
$rendered = $this->templating->render(
$params['template'], [
'user' => $user
]
);
$subject = $this->translator->trans('registration.email.welcome.subject'); // Same trans key, only for test
$this->sendEmailMessage($rendered, $subject, $params['from_email'], $user->getEmail());
}
答案 0 :(得分:3)
您的命令不处理config.yml
,然后它没有关于您当前语言环境的信息。您需要明确设置它:
/**
* @param UserInterface $user
*/
public function sendReflationEmailMessage(UserInterface $user)
{
$params = $this->parameters['registration']['reflation'];
$rendered = $this->templating->render(
$params['template'], [
'user' => $user
]
);
$this->translator->setLocale("en_EN");
$subject = $this->translator->trans('registration.email.welcome.subject'); // Same trans key, only for test
$this->sendEmailMessage($rendered, $subject, $params['from_email'], $user->getEmail());
}
答案 1 :(得分:0)
您还可以使用 ContainerAwareness :
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
class MyCommand extends ContainerAwareCommand
{
public function sendReflationEmailMessage(UserInterface $user)
{
$params = $this->parameters['registration']['reflation'];
$rendered = $this->templating->render(
$params['template'], [
'user' => $user
]
);
$subject = $this->getContainer()->get('translator')->trans('registration.email.welcome.subject');
$this->sendEmailMessage($rendered, $subject, $params['from_email'], $user->getEmail());
}
}
这应该处理你的 config.yml 。
但最佳做法是不注入完整的容器而是翻译,例如通过树枝。然后你可以做类似的事情:
$this->twig->getExtension('translator')->trans('registration.email.welcome.subject', array(), 'translation_domain');