2015-04-07 62 views
5

我在我的Yii2应用程序中使用基于关键字的翻译(我知道,这不是最佳选择,但我没有其他)。我已经使用关键字准备@app/messages/pl/app.php@app/messages/en/app.php文件与翻译字符串,而不是全功能的句子或单词:翻译源语言在Yii2应用程序中不起作用

<?php 
    return [ 
     'name_english'=>'Name in English', 
     'keywords_english'=>'Keywords in English' 
    ]; 
?> 

我已经把我的应用程序使用波兰语言作为默认:

'language' => 'pl', 
'sourceLanguage' => 'en', 

而且我调用翻译:

Yii::t('app', 'keywords_english'); 

一切正常,当语言实际上设置为基础,波兰pl):

enter image description here

但是,当我将其更改为英语en;无论是在运行时或更改应用程序配置)设置Yii::$app->language,不进行翻译和我得到keywords_english

enter image description here

我已经把die()@app/messages/pl/app.php@app/messages/en/app.php文件开始,我可以清楚地看到,当语言设置为英文时,第二个文件未被Yii2包含(应用程序运行如下),而当语言为波兰文时,包含第一个文件,并且该应用程序流程中断die()

我错过了什么?为什么Yii2不使用@app/messages/en/app.php文件的翻译,如果语言设置为Englishen)?

编辑:默认情况下,我没有改变默认i18n组件配置在我的应用程序的配置,因为我发现没有必要的。翻译文件存储在默认位置(@app/messages/<language>/),并使用默认类别(yii\i18n\PhpMessageSource)。这适用于除sourceLanguage之外的所有语言。在某些时候,我试图改变配置:

'i18n' => [ 
    'translations' => [ 
     '*' => [ 
      'class' => 'yii\i18n\PhpMessageSource', 
      'sourceLanguage' => 'en', 
      'basePath' => '@app/messages' 
     ], 
    ], 
], 

但是,它并没有带来变化(何必呢 - 它仍然使用默认设置)。

+0

中设置的类别设置从配置显示'i18n' –

+0

查看更新的问题。我没有以任何方式配置'i18n'。我为什么要?我想使用默认设置,这应该适用于'en',如果它适用于'pl',对吧? – trejder

+1

尝试:''translations'=> [''app''=>'''''>'yii \ i18n \ PhpMessageSource', 'basePath'=>'@app/messages', 'sourceLanguage' =>'en_US', 'fileMap'=> [ 'app'=>'app.php', ], ],' –

回答

6

根据samdark at Yii Forum,这是设计。如果language = sourceLangage,则不执行翻译。

要解决这个问题并强制转换,必须将forceTranslation设置为true

因此,必须添加/修改i18n成分components应用程序的配置一节中类似这样的方式:

'i18n' => [ 
    'translations' => [ 
     'app' => [ 
      'class' => 'yii\i18n\PhpMessageSource', 
      'forceTranslation' => true 
     ], 
    ], 
], 
1

解决方案:

'translations' => [ 
      'app*' => [ 
       'class' => 'yii\i18n\PhpMessageSource', 
       'basePath' => '@app/messages', 
       'sourceLanguage' => 'en_US', 
       'fileMap' => [ 
        'app' => 'app.php', 
       ], 
      ], 

答案的评论:

1)'sourceLanguage' => 'en_US' - 您必须使用完整的语言环境。由于英文区域设置可能是en_US,en_UK和e.t.c. The format for the language/locale is ll-CC where ll is a two- or three-letter lowercase code for a language according to ISO-639 and CC is the country code according to ISO-3166. from [doc][1]

2)在关键使用类别。并在Yii::t('category'...)