ทำโปรเจค yii แบบหลายภาษา ไทย อังกฤษ ญี่ปุ่น หรือประเทศอื่น
- สร้าง folder common\messages ในโพลเดอร์โปรเจค
- สร้างไฟล์ common\config\i18n.php ตามตัวอย่าง
[code language=”php”]
<?php
return [
‘languages’ => [
‘US’,
‘JP’,
‘TH’,
], /* Add languages to the array for the language files to be generated. */‘except’ => [
‘.git’,
‘.gitignore’,
‘.gitkeep’,
‘.hgignore’,
‘.hgkeep’,
‘.svn’,
‘/messages’,
‘/vendor’,
],/* exclude file */
‘format’ => ‘php’,
‘messagePath’ => __DIR__ . DIRECTORY_SEPARATOR . ‘..’ . DIRECTORY_SEPARATOR . ‘messages’,
‘only’ => [‘*.php’],
‘overwrite’ => true,
‘removeUnused’ => false,
‘sort’ => true,
‘sourcePath’ => __DIR__. ‘..’ . DIRECTORY_SEPARATOR . ‘..’ . DIRECTORY_SEPARATOR . ‘..’ . DIRECTORY_SEPARATOR,
‘translator’ => ‘Yii::t’
];
[/code] - เปิดไฟล์ common\config\main.php เพิ่ม language(ภาษา default), sourceLanguage ภาษาที่ใช้เป็นหลัก ใช้ en-US เป็นหลัก เพราะเวลาให้ชาติอื่นแปลจะง่ายกว่าแปลจากภาษาไทย สองตัวนี้ต้องต่างกันนะครับ ไม่งั้นมันจะไม่แปลให้ และเพิ่ม 18n ใน components
[code language=”php”]
<?php
return [
…
‘components’ => [
‘cache’ => [
‘class’ => ‘yii\caching\FileCache’,
],
‘i18n’ => [
‘translations’ => [
‘common*’ => [
‘class’ => ‘yii\i18n\PhpMessageSource’,
‘basePath’ => ‘@common/messages’,
],
],
‘on missingTranslation’ => [‘app\components\TranslationEventHandler’, ‘handleMissingTranslation’],
],
],
…
‘language’ => ‘TH’, /* must difren sourceLanguage */
‘sourceLanguage’ => ‘US’,
…
];
[/code] - เปิด view ที่จะแปลขึ้นมา เช่น D:\xampp\htdocs\YiiAdvanced\frontend\views\site\index.php เพิ่ม
[code language=”php”]
<?php echo Yii::t(‘common’, ‘Congratulations!’); ?>
[/code] - เปิด command cd ไปที่เราเก็บ project เช่น
[code language=”php”]
cd D:\xampp\htdocs\YiiAdvanced
yii message/extract @common/config/i18n.php
[/code] - เปิดไฟล์ใน common/messages ที่สร้าง folder ตามเงื่อนไขในไฟล์ i18n.php และ คอนฟิกใน i18n ใส่คำแปลไป เช่น
[code language=”php”]
‘Congratulations!’ => ‘สำเร็จแล้ว’;
[/code] - ชื่อไฟล์ คือ index ของ translations ถ้าเราต้องการแยกตัวแปลภาษา frontend กับ backend ออกจากกันก็แก้ i18n เป็น
[code language=”php”]
‘components’ => [
…
‘i18n’ => [
‘translations’ => [
‘frontend*’ => [
‘class’ => ‘yii\i18n\PhpMessageSource’,
‘basePath’ => ‘@common/messages’,
],
‘backend*’ => [
‘class’ => ‘yii\i18n\PhpMessageSource’,
‘basePath’ => ‘@common/messages’,
],
],
],
…
],
[/code]
เวลาใช้ก็
[code language=”php”] <?php echo Yii::t(‘frontend’, ‘Translatable String’); ?>[/code]
[code language=”php”] <?php echo Yii::t(‘backend’, ‘Translatable String’); ?>[/code] - ถ้าต้องการเพิ่มตัวแปลใหม่ก็ทำขั้นตอนที่ 5 และ 6 ใหม่อีกครั้ง
- มีภาค 2 การเปลี่ยนภาษา YII 2 Widget เปลี่ยนภาษา
- มีภาค 3 เกี่ยวกับการเก็บข้อมูลลงฐานข้อมูล ทำตาราง yii 2 ให้เก็บหลายภาษา
About the author