การทำให้เป็นสากล (Internationalization)
ไฟล์สำหรับการทำให้เป็นสากล
ในปลั๊กอิน ไฟล์สำหรับหลายภาษา (multi-language files) ทั้งฝั่ง frontend และ backend จะถูกเก็บไว้ในโฟลเดอร์ src/locale ครับ/ค่ะ
|- /plugin-i18n
|- /src
|- /locale # โฟลเดอร์สำหรับหลายภาษา
|- en-US.ts # ภาษาอังกฤษ
|- zh-CN.ts # ภาษาจีน
คุณสามารถเพิ่มรายการคำแปล (translation entries) ลงในไฟล์หลายภาษาที่เกี่ยวข้อง (/src/locale/${lang}.ts) ได้เลยครับ/ค่ะ หากเป็นการเพิ่มไฟล์หลายภาษาเป็นครั้งแรก คุณจะต้องรีสตาร์ทแอปพลิเคชันเพื่อให้การเปลี่ยนแปลงมีผลครับ/ค่ะ คุณสามารถตรวจสอบ API app:getLang เพื่อยืนยันว่ารายการคำแปลถูกเพิ่มสำเร็จแล้วหรือไม่
URL เริ่มต้น: http://localhost:13000/api/app:getLang?locale=zh-CN
API ที่เกี่ยวข้องกับ i18n
- server
- app.i18n
- app.t(text, options)
- ctx.i18n
- ctx.t(text, options)
- plugin.t()
- client
- ctx.i18n
- ctx.t(text, options)
- plugin.t()
- useT()
- utils
- react-i18next
- useTranslation(ns)
- withTranslation(ns)
ฝั่ง Server
app.i18n server
app.i18n คือ i18n instance แบบ Global ที่มักจะใช้ใน CLI ครับ/ค่ะ เช่น ใช้ร่วมกับ inquirer เพื่อสร้างการโต้ตอบใน Command Line
import select from '@inquirer/select';
import input from '@inquirer/input';
export class PluginSampleI18nServer extends Plugin {
load() {
this.app.command('test-i18n').action(async () => {
const answer1 = await select({
message: 'Select a language',
choices: [
{
name: '中文',
value: 'zh-CN',
},
{
name: 'English',
value: 'en-US',
},
],
});
await this.app.changeLanguage(answer1);
const answer2 = await input({
message: app.i18n.t('Enter your name'),
});
console.log(app.i18n.t(`Your name is {{name}}`, { name: answer2 }));
});
}
}
app.t(text, options) server
ctx.i18n server
ctx.i18n เป็น cloneInstance ของ app.i18n แบบ Global ครับ/ค่ะ โดย ctx ของแต่ละ request จะเป็นอิสระต่อกันอย่างสมบูรณ์ และจะตอบกลับข้อมูลหลายภาษาตามภาษาของไคลเอนต์
พารามิเตอร์ของคำขอจากไคลเอนต์สามารถใส่ไว้ใน query string ได้ครับ/ค่ะ
GET /?locale=en-US HTTP/1.1
Host: localhost:13000
หรือจะใส่ไว้ใน request headers ก็ได้ครับ/ค่ะ (แนะนำ)
GET / HTTP/1.1
Host: localhost:13000
X-Locale: en-US
ตัวอย่าง
export class PluginSampleI18nServer extends Plugin {
load() {
this.app.use(async (ctx, next) => {
if (ctx.path === '/api/test-i18n') {
ctx.body = `${ctx.i18n.t('Hello')} ${ctx.i18n.t('World')}`;
}
await next();
});
}
}
ดูได้ที่ http://localhost:13000/api/test-i18n?locale=zh-CN
ctx.t(text, options) server
plugin.t() server
ฝั่ง Client
ctx.i18n client
ctx.t(text, options) client
plugin.t()
useT()
ฟังก์ชันยูทิลิตี้
tExpr(text) server client
react-i18next
useTranslation(ns) client
withTranslation(ns) client