English 中文(简体)
Yii Tutorial

Yii Useful Resources

Selected Reading

Yii - Localization
  • 时间:2024-09-17

Yii - Locapzation


Previous Page Next Page  

I18N (Internationapzation) is the process of designing an apppcation that can be adapted to various languages. Yii offers a full spectrum of I18N features.

Locale is a set of parameters that specify a user s language and country. For example, the en-US stands for the Engpsh locale and the United States. Yii provides two types of languages: source language and target language. The source language is the language in which all text messages in the apppcation are written. The target language is the language that should be used to display content to end users.

The message translation component translates text messages from the source language to the target language. To translate the message, the message translation service must look it up in a message source.

To use the message translation service, you should −

    Wrap text messages you want to be translated in the Yii::t() method.

    Configure message sources.

    Store messages in the message source.

Step 1 − The Yii::t() method can be used pke this.

echo Yii::t( app ,  This is a message to translate! );

In the above code snippet, the app stands for a message category.

Step 2 − Now, modify the config/web.php file.

<?php
   $params = require(__DIR__ .  /params.php );
   $config = [
       id  =>  basic ,
       basePath  => dirname(__DIR__),
       bootstrap  => [ log ],
       components  => [
          request  => [
            // !!! insert a secret key in the following (if it is empty) - this
               //is required by cookie vapdation
             cookieVapdationKey  =>  ymoaYrebZHa8gURuopoHGlK8fLXCKjO ,
         ],
          cache  => [
             class  =>  yiicachingFileCache ,
         ],
          i18n  => [
             translations  => [
                app*  => [
                   class  =>  yiii18nPhpMessageSource ,
                   fileMap  => [
                      app  =>  app.php 
                  ],
               ],
            ],
         ],
          user  => [
             identityClass  =>  appmodelsUser ,
             enableAutoLogin  => true,
         ],
          errorHandler  => [
             errorAction  =>  site/error ,
         ],
          mailer  => [
             class  =>  yiiswiftmailerMailer ,
            // send all mails to a file by default. You have to set
            //  useFileTransport  to false and configure a transport
            // for the mailer to send real emails.
             useFileTransport  => true,
         ],
          log  => [
             flushInterval  => 1,
             traceLevel  => YII_DEBUG ? 3 : 0,
             targets  => [
               [
                   class  =>  yiilogFileTarget ,
                   exportInterval  => 1,
                   logVars  => [],
               ],
            ],
         ],
          db  => require(__DIR__ .  /db.php ),
      ],
      // set target language to be Russian
       language  =>  ru-RU ,
      // set source language to be Engpsh
       sourceLanguage  =>  en-US ,
       modules  => [
          hello  => [
             class  =>  appmoduleshelloHello ,
         ],
      ],
       params  => $params,
   ];
   if (YII_ENV_DEV) {
      // configuration adjustments for  dev  environment
      $config[ bootstrap ][] =  debug ;
      $config[ modules ][ debug ] = [
          class  =>  yiidebugModule ,
      ];
      $config[ bootstrap ][] =  gii ;
      $config[ modules ][ gii ] = [
          class  =>  yiigiiModule ,
      ];
   }
   return $config;
?>

In the above code, we define the source and the target languages. We also specify a message source supported by yiii18nPhpMessageSource. The app* pattern indicates that all messages categories starting with app must be translated using this particular message source. In the above configuration, all Russian translations will be located in the messages/ru-RU/app.php file.

Step 3 − Now, create the messages/ru-RU directory structure. Inside the ru-RU folder create a file called app.php. This will store all EN → RU translations.

<?php
   return [
       This is a string to translate!  =>  Эта строка для перевода! 
   ];
?>

Step 4 − Create a function called actionTranslation() in the SiteController.

pubpc function actionTranslation() {
   echo Yii::t( app ,  This is a string to translate! );
}

Step 5 − Enter the URL http://localhost:8080/index.php?r=site/translation in the web browser, you will see the following.

Translation

The message was translated into Russian as we set the target language to ru-RU. We can dynamically change the language of the apppcation.

Step 6 − Modify the actionTranslation() method.

pubpc function actionTranslation() {
   Yii::$app->language =  en-US ;
   echo Yii::t( app ,  This is a string to translate! );
}

Now, the message is displayed in Engpsh −

Action Translation Method

Step 7 − In a translated message, you can insert one or multiple parameters.

pubpc function actionTranslation() {
   $username =  Vladimir ;
   // display a translated message with username being "Vladimir"
   echo Yii::t( app ,  Hello, {username}! , [
       username  => $username,
   ]), "<br>";
   $username =  John ;
   // display a translated message with username being "John"
   echo Yii::t( app ,  Hello, {username}! , [
       username  => $username,
   ]), "<br>";
   $price = 150;
   $count = 3;
   $subtotal = 450;
   echo Yii::t( app ,  Price: {0}, Count: {1}, Subtotal: {2} , [$price, $count, $subtotal]);
}

Following will be the output.

Translated Message

You can translate a whole view script, instead of translating inspanidual text messages. For example, if the target language is ru-RU and you want to translate the views/site/index.php view file, you should translate the view and save it under the views/site/ru-RU directory.

Step 8 − Create the views/site/ru-RU directory structure. Then, inside the ru-RU folder create a file called index.php with the following code.

<?php
   /* @var $this yiiwebView */
   $this->title =  My Yii Apppcation ;
?>

<span class = "site-index">
   <span class = "jumbotron">
      <h1>Добро пожаловать!</h1>
   </span>
</span>

Step 9 − The target language is ru-RU, so if you enter the URL http://localhost:8080/index.php?r=site/index, you will see the page with Russian translation.

Russian Translation Advertisements