TIP
מסמך זה תורגם על ידי בינה מלאכותית. לכל אי דיוק, אנא עיין בגרסה האנגלית
I18n בינלאומיות
תוספים ב-NocoBase תומכים בבינלאומיות (i18n) רב-לשונית הן בצד הלקוח (frontend) והן בצד השרת (backend). באמצעות מנגנון אחיד, תוכלו ליישם בקלות תוכן רב-לשוני בתוספים.
ניהול קבצי ריבוי שפות
קבצי ריבוי השפות של התוספים נשמרים באופן אחיד בספריית src/locale. מומלץ לתת להם שמות לפי השפה, לדוגמה:
|- /plugin-hello
|- /src
|- /locale
|- en-US.json # English language
|- zh-CN.json # Chinese language
כל קובץ שפה מייצא אובייקט 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 גלובלי
app.i18n הוא מופע ה-i18n הגלובלי, והוא מתאים לשימוש בתרחישי CLI או בתרחישים גלובליים של תוספים. ניתן לשלב אותו עם inquirer כדי ליישם אינטראקציות בשורת הפקודה:
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) משמשת לתרגום טקסט ותומכת במשתני תבנית.
i18n בהקשר הבקשה
האובייקט ctx.i18n של כל בקשה הוא מופע משוכפל של מופע ה-i18n הגלובלי, והוא מגיב באופן עצמאי עם מידע רב-לשוני בהתאם לשפת הלקוח.
הגדרת שפת הלקוח
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)