我正在使用Yii2框架,并且已经使用这个指南配置了i18n组件。http:/thecodeninja.net201412i18n-with-yii-2-advanced-template。
因此,我现在可以在我的php文件中使用以下方法翻译字符串 Yii::t()
函数来提取可翻译的字符串。可翻译的字符串是用 $ ./yii message/extract
控制台命令,生成正确的翻译文件。
我现在需要显示存储在数据库中的字符串的翻译。
我可以使用 Yii:t()
用一个变量而不是字符串作为参数,就像这样
echo Yii:t('app', $some_string_from_db );
并建立一个新的php文件,其中包含一些代码,如以下所示
<?php
function dbStringsToTranslate() {
$o = Yii::t('app','db english string 1');
$o.= Yii::t('app','db english string 2');
$o.= Yii::t('app','db english string 3');
return $o;
}
这样一来 $ ./yii message/extract
命令会找到所需的翻译。
这是好的,但当然 $ ./yii message/extract
在我使用 Yii:t()
与变量。
Skipping line 39. Make sure both category and message are static strings.
我认为这不是什么大问题,但是,我的问题是。
这是一个正确的方式来翻译数据库中的字符串吗?
有没有更好的方法来实现?
你可以看看这个扩展。https:/github.comcreocoderyii2可翻译的。 它允许将行为附加到模型上,以支持多种语言。
我现在正在一个项目中使用它,它很容易使用。
我也有同样的问题,我找到了解决方法,用 该模块. 在模块配置中,你有 "tables "数组,你可以在数组中指定哪个表的哪些字段应该被翻译。然后,模块有自己的'scan'操作(相当于messageextract),它将所有可翻译的字符串添加到数据库中(使用 DbMessageSource):所有的Yii::t,指定的数据库字段,以及更多(甚至是javascript,查看文档)。它也有一个很好的用户界面来做翻译,非常棒!例如,通过下面的配置,表国籍的字段名将被扫描并添加到翻译中。
例如,通过以下配置,表国籍的字段名将被扫描并添加翻译(即国家名称)。
'modules' => [
'translatemanager' => [
'class' => 'lajax\translatemanager\Module',
...
'tables' => [ // Properties of individual tables
[
'connection' => 'db', // connection identifier
'table' => 'nationality', // table name
'columns' => ['name'], // names of multilingual fields
'category' => 'database-table-name',// the category is the database table name
'categoryPrefix' => 'lx-' //
]
]
],
],
你可以用一些假的生成php文件 Yii:t()
呼叫。例如,在输出中,这个文件会是这样的:
$filename = Yii::getAlias('@frontend/runtime/fake-category-translations.php');
$str = '<?php' . PHP_EOL;
foreach (Category::find()->all() as $category) {
$str .= "Yii::t('category', '{$category->name}');" . PHP_EOL;
}
file_put_contents($filename, $str);
在输出中,这个文件会是这样的。
<?php
Yii::t('category', 'Art & Design');
Yii::t('category', 'Creativity');
Yii::t('category', 'Educational');
Yii::t('category', 'Education');
Yii::t('category', 'Lifestyle');
Yii::t('category', 'Casual');
所以,现在你可以直接调用控制台方法来搜索未翻译的字符串。
php yii message/extract @frontend/messages/config.php