Yii2:如何翻译模块内的小部件

时间:2015-09-16 20:16:41

标签: php yii2 translation

我目前在模块中有一个小部件,我想创建一个消息目录,以便我可以从该文件夹中翻译模块字符串。

我遇到的问题是我无法让小部件从模块文件夹中获取翻译。

这是我的结构

frontend/modules/comments
frontend/modules/comments/Module.php
frontend/modules/comments/widgets/CommentsWidget.php
frontend/modules/comments/widgets/views/_form.php

-Module.php

namespace frontend\modules\comments;

use Yii;

class Module extends \yii\base\Module {

    public $controllerNamespace = 'frontend\modules\comments\controllers';

    public function init() {
    parent::init();
    $this->registerTranslations();
    }

    public function registerTranslations() {
    Yii::$app->i18n->translations['modules/comments/*'] = [
        'class' => 'yii\i18n\PhpMessageSource',
        'sourceLanguage' => 'en',
        'basePath' => '@frontend/modules/comments/messages',
        'fileMap' => [
        'modules/comments/comments' => 'comments.php',
        ]
    ];
    }

    public static function t($category, $message, $params = [], $language = null) {
    return Yii::t('modules/comments/' . $category, $message, $params, $language);
    }

}
  • _form.php这个

我使用以下代码来调用翻译。

Module::t('comments', 'COMMENT_REPLY')

但它似乎不起作用。有任何想法吗? 提前谢谢!

1 个答案:

答案 0 :(得分:1)

有同样的问题。 这是因为您在init()方法中注册了翻译(当创建模块实例时)。您可以将registerTranslations()方法更改为静态方法:

public function init()
{
    // ...

    self::registerTranslations();
}

public static function registerTranslations()
{
    // ...
}

在使用Content::registerTranslations();之前,请在小部件中将其命名为Module::t()