lin_lin 2015-07-04 08:57:39 15758次浏览 4条评论 12 5 0

1) 在 /common/config/main.php 下添加如下代码:

'language'=>'en',
'components' => [
        'i18n' => [ 
                'translations' => [ 
                    'app' => [ 
                        'class' => 'yii\i18n\PhpMessageSource', 
                        'basePath' => '@common/messages', 
                        // 'sourceLanguage' => 'en-US', 
                        'fileMap' => [
                             'app' => 'app.php', 
                             'app/error' => 'error.php', 
                        ],
                    ],
                ],
            ], 
    ],

a) basePath :这条路径必须是适当的,目前我已经创建了一个messages文件夹放在common文件夹内,这样我就可以轻松地使用它的模块。

b) fileMap : 创建 app.php文件放在语言文件夹下,例如en/app.php和ru/app.php。

2)创建 common/messages/en/app.php 英文翻译文件 :

<?php
return [ 
		'Welcome_flag'=>'welcome here from common/messages in English', 
		'Goodbye_flag'=>'goodbye here from common/messages in English', 
];
?>

创建 common/messages/ru/app.php 俄文翻译文件

<?php
return [ 
		'Welcome_flag'=>'welcome here from common/messages in Russian', 
		'Goodbye_flag'=>'goodbye here from common/messages in Russian', 
];
?>

3)在SiteController.php下,代码如下:

public function actionIndex()
    {   
        Yii::$app->language = 'en';  //指定使用哪个语言翻译  如果用俄文则是 Yii::$app->language = 'ru';
        echo Yii::t('app', 'Goodbye_flag');
    }

4)测试如下:http://localhost:8888/project/frontend/web/index.php

页面将会输出 welcome here from common/messages in english

详细参看

觉得很赞
  • 评论于 2015-07-04 10:33 举报

    好贴必赞

    1 条回复
    评论于 2015-07-04 11:04 回复

    相互学习 :)

  • 评论于 2016-08-30 20:14 举报

    入门贴,写的不错!

  • 评论于 2017-08-25 14:53 举报

    为什么我改成
    'language'=>'en',
    'components' => [

        'i18n' => [ 
                'translations' => [ 
                    '*' => [ 
                        'class' => 'yii\i18n\PhpMessageSource', 
                        'basePath' => '@common/messages', 
                        // 'sourceLanguage' => 'en-US', 
                        'fileMap' => [
                             'language' => 'language.php', 
                             'app/error' => 'error.php', 
                        ],
                    ],
                ],
            ], 
    ],
    

    创建 common/messages/en/language.php 英文翻译文件 :
    <?php
    return [

    	'Welcome_flag'=>'welcome here from common/messages in English', 
    	'Goodbye_flag'=>'goodbye here from common/messages in English', 
    

    ];
    ?>

    页面中的改成使用language,为什么最后没效果呢
    Yii::t('language', 'Goodbye_flag');

  • 评论于 2018-12-25 21:53 举报

    数据库里的数据中英文怎么实现呢

您需要登录后才可以评论。登录 | 立即注册