10月CMS - 使用RainLab翻译插件翻译后端

时间:2018-03-01 16:31:25

标签: php octobercms octobercms-plugins octobercms-backend

在我的应用程序中,我有一个自定义插件,其形式大约有80个可翻译字段。该表单将在后端(针对管理员)和前端(针对最终用户)中提供相同的标签。

我想使用Rainlab Translate插件翻译所有字段的标签,以便管理员可以轻松更改它们以满足他们的需求。

问题是所有后端翻译都存储在文件系统中(例如/plugins/my-plugin/lang/en/lang.php)。

是否可以使用Rainlab Translate插件管理自定义插件的翻译?这样可以避免在php翻译文件和数据库之间出现重复。

到目前为止,我已经安装了Rainlab Translate插件,用法语和德语翻译前端。

谢谢你们!

2 个答案:

答案 0 :(得分:1)

我想出了一个创建自定义插件的解决方案,该插件扩展了10月CMS后端转换器服务。我已将以下代码添加到我的插件的boot()方法中:

>>> request = {"data":{"a":[{"data": {"b": {"data": {"c": "d"}}}}]}}
>>> unwrap_data(request)
{'a': [{'b': {'c': 'd'}}]}

我创建了一个Translator类,它扩展了默认类并实现了翻译的数据库查找。如果没有找到翻译,它还会回退到默认的基于数组文件的翻译。

 // Custom Backend Translator that handles the Backend localisation with the Rainlab Translator plugin
    $this->app->singleton('translator', function ($app) {
        $loader = $app['translation.loader'];

        // When registering the translator component, we'll need to set the default
        // locale as well as the fallback locale. So, we'll grab the application
        // configuration so we can easily get both of these values from there.
        $locale = $app['config']['app.locale'];
        // extending October CMS Translator class
        $trans = new Translator($loader, $locale);
        // setting locale to message
        Message::$locale = $locale;

        $trans->setFallback($app['config']['app.fallback_locale']);

        return $trans;
    });

以下Message类的代码:

<?php namespace Author\MyPlugin\Classes\Translation;

use Author\MyPlugin\Classes\Translation\Message as Message;

class Translator extends \October\Rain\Translation\Translator
{
    /**
     * Get the translation for the given key.
     *
     * @param  string $key
     * @param  array $replace
     * @param  string $locale
     * @return string
     */
    public function get($key, array $replace = [], $locale = null)
    {
        // getting translation from database
        $message = Message::trans($key);
        // if there's a translation we return it
        if ($message != null && $message !== $key) {
            return $message;
        }
        // otherwise fallback to file array translations
        return parent::get($key, $replace, $locale);
    }
}

欢迎任何有关此解决方案的反馈。

答案 1 :(得分:0)

理论上我认为应该可以返回通过Translate实例加载的数组,而不是返回预定义的数组。

因此,不是在lang/en/lang.php中返回一个简单数组,而是使用与前端键匹配的键填充数组。

所以而不是:

return [
    'key' => 'language-string'
];

做这样的事情:

  • 检索所有语言密钥
  • 遍历所有键并获取正确的语言字符串
  • 将关键字添加到关联数组

更新:

我能找到的最快捷的方法是创建一个包含所有相关密钥的配置文件,并在rainlab_translate_messages表的查询中使用它。 您将所有值转换为正确的格式(assoc数组),并在lang.php文件中返回此值。

这是疯狂的hacky,感觉很脏,可能非常容易出错。但应该工作。

注意:如果有人想出更好的方法,请使用它。这不是我建议的。但是,嘿,我猜它有效。

相关问题