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


Yii2: How to translate a widget that is inside a module

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

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

这是我的结构

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

但它似乎不起作用。什么好主意吗?提前感谢!

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

public function init()
{
    // ...
    self::registerTranslations();
}
public static function registerTranslations()
{
    // ...
}

在使用Module::t()之前先在widget中命名为Content::registerTranslations();