{ the code ninja }

i18n with Yii 2 Advanced Template

In this post, I will show you my workflow for internationalization of Yii based projects.

We will configure sane paths, logically dividing the frontend and backend. We will also use the yii cli tool to generate the translation files for us. Let’s get started.

  1. Create messages directory inside the common directory.
  2. Create a file called i18n.php inside common/config directory.
  3. Paste the following block of code inside i18n.php.
    • Make sure to add all required languages to ‘languages’ array. In the above example I have added Portuguese.
  4. Add the i18n component to your common/main.php configuration as follows:
  5. You can now:
    • Set the language in common configuration i.e.  'language' => 'pt-PT' inside common/main.php.
    • Set the language at runtime i.e. Yii::$app->language = 'pt-PT'
    • See the Yii 2.0 Guide on Internationalization for more details on setting a language.
  6. In your frontend and backend code, use the following method to create i18n supported strings respectively.

  7. Run  yii message/extract @common/config/i18n.php to generate the translation files inside common/messages.
  8. Yii message will generate the translation files as follows:
  9. The files frontend.php and backend.php are now ready to edit the Portuguese translations 🙂

There you have it! Once set up correctly, just run step #7 every time you add new translatable strings to your app. Yii CLI tool automatically and safely merges existing translations with the new strings and you can translate the new strings in the generated files.

Further Reading

http://www.yiiframework.com/doc-2.0/guide-tutorial-i18n.html
http://www.yiiframework.com/doc-2.0/yii-baseyii.html#t()-detail

Bonus Tip

You can further organize the translatable files i.e.  Yii::t('frontend/post', 'Translatable String'); will generate common/messages/pt-PT/frontend/post.php with all translatable strings inside.

Exit mobile version