oorrwullie / yii2-babelfishfood
Yii2 Babelfish共生体的语言切换伴侣
0.7.4
2017-07-20 00:39 UTC
Requires
- yiisoft/yii2: *
This package is not auto-updated.
Last update: 2024-09-15 01:46:46 UTC
README
Yii2 Babelfish共生体的语言切换伴侣。它也可以用作完整的独立解决方案,快速为使用标准Yii2高级模板构建的任何网站启用i18n支持。
主要功能
- 预先填充了115种语言和方言的数据库,以便快速开始。 (您可以使用CRUD或迁移添加更多。)只需更改语言的激活属性即可添加或删除对语言的支持。
- 默认配置为使用GetText po文件。 (可以切换以支持基于数据库的翻译。)
- 根据浏览器偏好检测首选语言。
- 语言切换小部件以本地格式和本地字母显示语言。
- 小部件将语言保存为访客的cookie和在登录用户的用户表中。
- 为语言管理提供完整的CRUD实现。
安装
安装此扩展的首选方式是通过 composer。
运行以下命令
php composer.phar require --prefer-dist oorrwullie/yii2-babelfishfood "*"
或添加
"oorrwullie/yii2-babelfishfood": "*"
到您的 composer.json
文件的require部分。
配置
一旦安装了扩展
在数据库中创建语言表并添加语言列
php yii migrate --migrationPath=@vendor/oorrwullie/yii2-babelfishfood/migrations
您可以使用数据库中该语言的激活列选择受支持的语言。我们建议编写迁移来更新您的活动语言,并关闭您未使用的任何默认语言。
在 common/config/main.php 中配置组件
'components' => [ 'babelfishfood' => [ 'class' => 'oorrwullie\babelfishfood\components\BFFComponent', 'cookieName' => 'language', // Name of the cookie. 'cookieDomain' => 'example.com', // Domain of the cookie. 'expireDays' => 64, // The expiration time of the cookie is 64 days. 'callback' => function() { if (!\Yii::$app->user->isGuest) { $user = \Yii::$app->user->identity; $user->language = \Yii::$app->language; $user->save(); } } ] ]
您需要为每个希望翻译正常工作的应用启动组件:在前端/config/main.php 中
'language' => 'en', 'bootstrap' => ['babelfishfood'],
如果您希望在后端也有切换器,请在此处进行相同的操作。
配置翻译提取
在 common/config/main.php 中需要填写如下所示的i18n部分:
'i18n' => [ 'translations' => [ 'menu*' => [ 'class' => 'yii\i18n\GettextMessageSource', 'useMoFile' => false, 'basePath' => '@common/messages', ], 'home*' => [ 'class' => 'yii\i18n\GettextMessageSource', 'useMoFile' => false, 'basePath' => '@common/messages', ], 'base*' => [ 'class' => 'yii\i18n\GettextMessageSource', 'useMoFile' => false, 'basePath' => '@common/messages', ], 'global*' => [ 'class' => 'yii\i18n\GettextMessageSource', 'useMoFile' => false, 'basePath' => '@common/messages', ], ], ],
要使用内置的CRUD管理语言,请将以下内容添加到 backend/config/main.php 中
'modules' => [ 'bff' => [ 'class' => 'oorrwullie\babelfishfood\BabelFishFood', ], ],
实现
指定要翻译的文本
将待翻译的文本包装如下
echo \Yii::t('app', 'This is a string to translate!');
要编译翻译到po文件中,导航到您的项目根目录并运行
./yii message/extract @oorrwullie/babelfishfood/config/i18n.php
上述命令有点长。在 oorrwullie/yii2-babelfishfood 中有一个名为 i18n 的bash脚本。您可以将它复制到项目根目录,并通过运行
./i18n
在视图中使用小部件
<?= \oorrwullie\babelfishfood\BFF::widget(); ?>
您可以更改下拉小部件的标签(默认为“语言:”),语言可以是普通或大写(默认为大写)。例如
<?= \oorrwullie\babelfishfood\BFF::widget([ 'upperCase' => FALSE, 'label' => '<i class="fa fa-language"></i>', ]); ?>
使用CRUD
导航到您的后端url + bff,如下所示: www.example.com/backend/bff