TIP
이 문서는 AI로 번역되었습니다. 부정확한 내용이 있을 경우 영어 버전을 참조하세요
I18n 국제화
NocoBase 플러그인에서는 프런트엔드와 백엔드 모두에서 다국어 국제화(i18n)를 지원합니다. 통합된 메커니즘을 통해 플러그인에서 다국어 콘텐츠를 쉽게 구현할 수 있습니다.
다국어 파일 관리
플러그인의 다국어 파일은 src/locale 디렉터리에 통합하여 저장됩니다. 파일명은 언어 파일명으로 지정하는 것을 권장합니다. 예를 들어 다음과 같습니다:
|- /plugin-hello
|- /src
|- /locale
|- en-US.json # 영어
|- zh-CN.json # 중국어
각 언어 파일은 해당 언어의 모든 번역 항목을 포함하는 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
미들웨어에서 사용
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)