如何在控制器内生成 symfony2 翻译? [英] How to generate symfony2 translations inside controller?

查看:32
本文介绍了如何在控制器内生成 symfony2 翻译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Symfony2 项目.我正在使用 JMSTranslationsBundle.

Symfony2 project. I'm using JMSTranslationsBundle.

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

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

如何为 .xliff 文件中的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?

推荐答案

可用的提取方法,它说明您的案例没有可用的自动提取.

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

您需要使用 trans (或任何其他解释的方法)在您的模板或控制器中.如果没有这个提示,提取器将无法找到您的消息.我个人在我的一个项目中使用了 TranslationContainerInterface.

您只需在控制器中定义一个新方法,该方法返回待翻译"字符串:

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

这篇关于如何在控制器内生成 symfony2 翻译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆