Yii Framework Translation

Translation หรือการแปลภาษา เป็นหัวข้อหนึ่งของ I18N (Internationalization)
ซึ่งการแปลภาษาใน Yii จะต้องการ Property 2 ตัวในการแปลภาษาคือ Source language และ Target language

Source language
เป็นภาษาหลักที่ใช้เขียนโปรแกรม กำหนดด้วย property $sourceLanguage มีค่าปริยายคือ 'en_us' (US English)

Target language
เป็นภาษาที่แสดงผลให้ user เห็น กำหนดด้วย property $language ซึ่งถ้าไม่ได้ระบุไว้ ระบบจะดึงเอา source language มาใช้

ตัวอย่าง การกำหนดให้ target language เป็นภาษาไทย

ที่ไฟล์ protected/config/main.php เข้าไปเพิ่ม config property ตามนี้

return array(
	...
	// the language that the application is written in. 
	'sourceLanguage' => 'en_us', 

	// the language that the user is using and the application should be targeted to
	'language' => 'th', 
	...
);

โดย Yii จะแบ่งการแปลภาษาออกเป็น 2 ระดับคือ

Message Translation

แปลที่ตัวข้อความ ก่อน render (อยู่ใน protected/messages/{LocaleID}/CategoryID.php)

ตัวอย่าง การกำหนด Message Translation

  1. เรียกใช้ Yii::t('categoryName', 'message to be translated') ในจุดที่ต้องการให้มีการแปลภาษา 
    เช่น ต้องการ เพิ่มจุดที่สามารถแปลภาษาได้ ในไฟล์ /protected/views/employee/index.php
    จากเดิม
    <h1>Employees</h1>
    
    ก็เข้าไปแก้ใขให้เป็น
    <h1><?php echo Yii::t('Employee', 'Employees')?></h1>
    
    จากด้านบน categoryName คือ Employee, message to be translated คือ Employees
    เดี๋ยวขั้นต่อไปเราจะเอา Employee ไปสร้างเป็นชื่อไฟล์ และเอา Employees ไปใช้เป็น Key ในการ config ภาษา
  2. สร้างไฟล์แปลภาษาที่ protected/messages/{LocaleID}/{CategoryName}.php
    เช่น 
    Yii Message Translation Tree
    จากด้านบน {LocaleID} คือ th, {CategoryName} คือ Employee, Department
  3. ไปตั้งค่าที่ไฟล์ภาษาที่สร้างขึ้นมา
    <?php
    
    return array (
    
         'Employees' => 'พนักงาน',
    	 'Department' => 'แผนก'
    
    );
    

**การแบ่ง CategoryName นอกจากจะมีข้อดีเรื่องความเป็นระเบียบแล้ว ยังมีประโยชน์กรณีที่ ข้อความเดียวกันแปลไม่เหมือนกันใน category ที่ต่างกันด้วย
เช่น ใน Employee.php ใช้ 'Employees' => 'พนักงาน' แต่ใน Department.php ใช้ 'Employees' => 'ลูกจ้าง'

File Translation

เป็นการแปลที่ view, แยกไฟล์ view ของแต่ละภาษาออกจากกัน (อยู่ใน protected/views/{Controler}/{LocaleID}/{FILES})
Yii จะ scan หาว่าใน view มีไฟล์ที่เป็น translated version ที่ตรงกับ target language หรือเปล่า ถ้ามีก็จะเลือกมาแสดงผล

ตัวอย่าง การกำหนด File Translation

  1. สร้างไฟล์ protected/views/{Controler}/{LocaleID}/{FILES}
    เช่น
    /protected/views/site/th/index.php
    /protected/views/employee/th/create.php
    
  2. อยากทำ translated version ของ Controller ไหนก็ copy ไฟล์มาวางใน folder {LocaleID} ได้เลย ง่ายมั่กๆ

    Yii File Translation Tree
  3. อยากแก้อะไรก็เรื่องของเธอละทีนี้

Post new comment

© 2010 Pangpond.. Theme by Kiwi Themes.