TIP
מסמך זה תורגם על ידי בינה מלאכותית. לכל אי דיוק, אנא עיין בגרסה האנגלית
בינאום
קובצי בינאום
בתוספים, קובצי ריבוי השפות עבור צד הלקוח וצד השרת נשמרים בתיקייה src/locale.
|- /plugin-i18n
|- /src
|- /locale # תיקיית ריבוי שפות
|- en-US.ts # שפה אנגלית
|- zh-CN.ts # שפה סינית
פשוט הוסיפו ערכי תרגום לקובצי ריבוי השפות המתאימים (/src/locale/${lang}.ts). אם זהו קובץ ריבוי שפות שנוסף לראשונה, יש להפעיל מחדש את היישום כדי שהשינויים ייכנסו לתוקף. ניתן לבדוק את ה-API של app:getLang כדי לוודא שערכי התרגום נוספו בהצלחה.
כתובת ברירת מחדל: http://localhost:13000/api/app:getLang?locale=zh-CN
ממשקי API קשורים ל-i18n
- שרת
- app.i18n
- app.t(text, options)
- ctx.i18n
- ctx.t(text, options)
- plugin.t()
- לקוח
- ctx.i18n
- ctx.t(text, options)
- plugin.t()
- useT()
- כלי עזר
- react-i18next
- useTranslation(ns)
- withTranslation(ns)
שרת
app.i18n server
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: 'בחרו שפה',
choices: [
{
name: 'סינית',
value: 'zh-CN',
},
{
name: 'אנגלית',
value: 'en-US',
},
],
});
await this.app.changeLanguage(answer1);
const answer2 = await input({
message: app.i18n.t('הזינו את שמכם'),
});
console.log(app.i18n.t(`שמכם הוא {{name}}`, { name: answer2 }));
});
}
}
app.t(text, options) server
ctx.i18n server
ctx.i18n הוא מופע משוכפל (cloneInstance) של app.i18n הגלובלי. כל ctx של בקשה הוא עצמאי לחלוטין ומספק מידע רב-לשוני בהתאם לשפת הלקוח.
פרמטרי בקשת הלקוח יכולים להיות ממוקמים ב-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('שלום')} ${ctx.i18n.t('עולם')}`;
}
await next();
});
}
}
צפו ב-http://localhost:13000/api/test-i18n?locale=zh-CN
ctx.t(text, options) server
plugin.t() server
לקוח
ctx.i18n client
ctx.t(text, options) client
plugin.t()
useT()
פונקציות עזר
tExpr(text) server client
react-i18next
useTranslation(ns) client
withTranslation(ns) client