How to internationalize Yii applications?

Member

by gilbert , in category: PHP Frameworks , 2 years ago

How to internationalize Yii applications?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 2 years ago

@gilbert 

To internationalize Yii applications, you can follow these steps:

  1. Enable message translations: Open the config file main.php and add the following lines to the 'components' array:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
'i18n' => [
    'translations' => [
        'app*' => [
            'class' => 'yiii18nPhpMessageSource',
            'basePath' => '@app/messages',
            'sourceLanguage' => 'en-US',
            'fileMap' => [
                'app' => 'app.php',
                'app/error' => 'error.php',
            ],
        ],
    ],
],


  1. Create translation files: Create a directory named 'messages' under your main application directory, and then create subdirectories for each language you want to support (e.g. 'en-US', 'fr-FR', 'de-DE', etc.). In each language directory, create a file named 'app.php' (or whatever you specified in the 'fileMap' section above) and add the translation messages in key-value pairs.
  2. Use translation messages in your views or controllers: In your views or controllers, use the Yii::t() method to translate the messages. For example:
1
echo Yii::t('app', 'Hello World!');


This will output the translated message for the current language.

  1. Set the application language: You can set the application language in the main.php config file using the 'language' parameter:
1
'language' => 'en-US',


You can also change the language dynamically by setting the 'language' parameter of the Yii::$app object:

1
Yii::$app->language = 'fr-FR';


That's it! Your Yii application is now internationalized and ready to support multiple languages.