egg-i18n

可以为你的应用提供多语言的特性
功能
- 支持多种语言独立配置,统一存放在 config/locale/*.js 下( 兼容
config/locales/*.js
); - 提供 Middleware 为 View 提供
\_\_
, gettext
函数获取多语言文案; - 基于 URL 参数
locale
修改语言显示,同时会记录到 Cookie,下次请求会用 Cookie 里面的语言方案。
配置
默认处于关闭状态,你需要在 config/plugin.js
开启它:
exports.i18n = {
enable: true,
package: 'egg-i18n',
};
你可以修改 config/config.default.js
来设定 i18n 的配置项:
exports.i18n = {
defaultLocale: 'zh-CN',
queryField: 'locale',
cookieField: 'locale',
cookieDomain: '',
cookieMaxAge: '1y',
};
其实大部分时候,你只需要修改一下 defaultLocale
设定默认的语言。
编写你的 I18n 多语言文件
module.exports = {
"Email": "邮箱",
"Welcome back, %s!": "欢迎回来,%s!",
"Hello %s, how are you today?": "你好 %s, 今天过得咋样?",
};
module.exports = {
"Email": "Email",
};
或者也可以用 JSON 格式的文件:
{
"email": "邮箱",
"login": "帐号",
"createdAt": "注册时间"
}
使用 I18n 函数获取语言文本
I18n 为你提供 __
(Alias: gettext
) 函数,让你可以轻松获得 locale 文件夹下面的多语言文本。
NOTE: __ 是两个下划线哦!
- ctx.__ = function (key, value[, value2, ...]): 类似 util.format 接口
- ctx.__ = function (key, values): 支持数组下标占位符方式,如
ctx.__('{0} {0} {1} {1}'), ['foo', 'bar'])
ctx.gettext('{0} {0} {1} {1}'), ['foo', 'bar'])
=>
foo foo bar bar
Controllers 下的使用示例
module.exports = function* () {
this.body = {
message: this.__('Welcome back, %s!', this.user.name)
user: this.user,
};
};
View 文件下的使用示例
<li>{{ __('Email') }}: {{ user.email }}</li>
<li>
{{ __('Hello %s, how are you today?', user.name) }}
</li>
<li>
{{ __('{0} {0} {1} {1}'), ['foo', 'bar']) }}
</li>
修改应用的默认语言
你可以用下面几种方式修改应用的当前语言(修改或会记录到 Cookie),下次请求直接用设定好的语言。
优先级从上到下:
- query: /?locale=en-US
- cookie: locale=zh-TW
- header: Accept-Language: zh-CN,zh;q=0.5
3.0.0 (2025-01-11)
⚠ BREAKING CHANGES
- drop Node.js < 18.19.0 support
part of https://github.com/eggjs/egg/issues/3644
https://github.com/eggjs/egg/issues/5257
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
Summary by CodeRabbit
Based on the comprehensive changes, here are the updated release notes:
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Features
2.1.1 / 2019-04-30
fixes
others
2.1.0 / 2019-04-28
features
others
2.0.0 / 2017-11-10
others
1.2.0 / 2017-09-13
features
1.1.1 / 2017-04-19
- fix: config.i18n.dir should be config.i18n.dirs (#6)
1.1.0 / 2017-01-13
- feat: add ctx.locale getter (#5)
- deps: upgrade deps (#4)
1.0.2 / 2016-08-26
1.0.1 / 2016-08-16
- fix: use loader.getLoadUnits from egg-core (#2)
1.0.0 / 2016-08-02