I18n การรองรับหลายภาษา
ในปลั๊กอินของ NocoBase รองรับการรองรับหลายภาษา (i18n) ทั้งฝั่ง frontend และ backend ครับ/ค่ะ ด้วยกลไกที่เป็นหนึ่งเดียว ทำให้คุณสามารถสร้างเนื้อหาหลายภาษาในปลั๊กอินได้อย่างง่ายดาย
การจัดการไฟล์หลายภาษา
ไฟล์หลายภาษาของปลั๊กอินจะถูกจัดเก็บไว้ในไดเรกทอรี src/locale ครับ/ค่ะ โดยแนะนำให้ตั้งชื่อไฟล์ตามรหัสภาษา เช่น:
|- /plugin-hello
|- /src
|- /locale
|- en-US.json # ภาษาอังกฤษ
|- zh-CN.json # ภาษาจีน
ไฟล์ภาษาแต่ละไฟล์จะ export (ส่งออก) เป็นออบเจกต์ JSON ซึ่งประกอบด้วยข้อความแปลทั้งหมดสำหรับภาษานั้น ๆ ครับ/ค่ะ เช่น:
// zh-CN.json
{
"Hello": "你好",
"World": "世界",
"Enter your name": "请输入你的名字",
"Your name is {{name}}": "你的名字是 {{name}}"
}
// en-US.json
{
"Hello": "Hello",
"World": "World",
"Enter your name": "Enter your name",
"Your name is {{name}}": "Your name is {{name}}"
}
เมื่อเพิ่มไฟล์ภาษาเป็นครั้งแรก คุณจะต้องรีสตาร์ทแอปพลิเคชันเพื่อให้การเปลี่ยนแปลงมีผลครับ/ค่ะ คุณสามารถตรวจสอบว่าข้อความแปลมีผลหรือไม่ผ่าน API ได้ที่:
http://localhost:13000/api/app:getLang?locale=zh-CN
อินสแตนซ์ i18n แบบ Global
app.i18n คืออินสแตนซ์ i18n แบบ Global ซึ่งเหมาะสำหรับสถานการณ์ที่ใช้งานใน CLI หรือในปลั๊กอินแบบ Global ครับ/ค่ะ สามารถใช้ร่วมกับ 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.i18n.t(text, options) ใช้สำหรับแปลข้อความ และรองรับตัวแปรในรูปแบบ template ครับ/ค่ะ
i18n ใน Request Context
ctx.i18n ของแต่ละ request เป็นอินสแตนซ์ที่โคลนมาจาก i18n แบบ Global ซึ่งจะตอบสนองข้อมูลหลายภาษาได้อย่างอิสระตามภาษาของไคลเอนต์ครับ/ค่ะ
การตั้งค่าภาษาของไคลเอนต์
GET /?locale=en-US HTTP/1.1
Host: localhost:13000
GET / HTTP/1.1
Host: localhost:13000
X-Locale: en-US
การใช้งานใน Middleware
export class PluginSampleI18nServer extends Plugin {
load() {
this.app.use(async (ctx, next) => {
if (ctx.path === '/api/test-i18n') {
ctx.body = ctx.t('Hello', { ns: '@my-project/plugin-hello' });
}
await next();
});
}
}
เมื่อเข้าถึง http://localhost:13000/api/test-i18n?locale=zh-CN จะได้รับค่า 你好 กลับมาครับ/ค่ะ
i18n ภายในปลั๊กอิน
ภายในปลั๊กอินสามารถใช้ plugin.t(key, options) เพื่อเรียกข้อความแปลได้โดยตรงครับ/ค่ะ:
export class PluginSampleI18nServer extends Plugin {
load() {
this.app.use(async (ctx, next) => {
if (ctx.path === '/api/plugin-i18n') {
ctx.body = this.plugin.t('Hello');
}
await next();
});
}
}
plugin.t(text) เทียบเท่ากับ ctx.t(text, { ns })
API ที่เกี่ยวข้อง
- app.i18n
- app.t(text, options)
- ctx.i18n
- ctx.t(text, options)
- plugin.t()
- tExpr(text, options)