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}}"
}
初次添加语言文件,需要重启应用才能生效。可以通过接口校验翻译词条是否生效:
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)