koa locales, i18n solution for koa:
- All locales resources location on
options.dirs
. - resources file supports:
*.js
,*.json
,*.yml
,*.yaml
and*.properties
, see examples. - Api:
__(key[, value, ...])
,__n(key, count[, value, ...])
. - Auto detect request locale from
query
,cookie
andheader: Accept-Language
.
$ npm install koa-locales --save
const koa = require('koa');
const locales = require('koa-locales');
const app = koa();
const options = {
dirs: [__dirname + '/locales', __dirname + '/foo/locales'],
};
locales(app, options);
Patch locales functions to koa app.
- {Application} app: koa app instance.
- {Object} options: optional params.
- {String} functionName: locale function name patch on koa context. Optional, default is
__
. - {String} functionnName: locale function (with plurals management) name patch on koa context. Optional, default is
__n
. - {String} dirs: locales resources store directories. Optional, default is
['$PWD/locales']
. - {String} defaultLocale: default locale. Optional, default is
en-US
. - {String} queryField: locale field name on query. Optional, default is
locale
. - {String} cookieField: locale field name on cookie. Optional, default is
locale
. - {String} cookieDomain: domain on cookie. Optional, default is
''
. - {Object} localeAlias: locale value map. Optional, default is
{}
. - {String|Number} cookieMaxAge: set locale cookie value max age. Optional, default is
1y
, expired after one year.
- {String} functionName: locale function name patch on koa context. Optional, default is
locales({
app: app,
dirs: [__dirname + '/app/locales'],
defaultLocale: 'zh-CN',
});
The key options.localeAlias
allows to not repeat dictionary files, as you can configure to use the same file for es_ES for es, or en_UK for en.
locales({
localeAlias: {
es: es_ES,
en: en_UK,
},
});
Get current request locale text.
async function home(ctx) {
ctx.body = {
message: ctx.__('Hello, %s', 'fengmk2'),
};
}
Examples:
__('Hello, %s. %s', 'fengmk2', 'koa rock!')
=>
'Hello fengmk2. koa rock!'
__('{0} {0} {1} {1} {1}', ['foo', 'bar'])
=>
'foo foo bar bar bar'
__('{a} {a} {b} {b} {b}', {a: 'foo', b: 'bar'})
=>
'foo foo bar bar bar'
Get current request locale text with plural.
Works with package make-plural package. Support approximately 200 languages.
async function home(ctx) {
ctx.body = {
message: ctx.__n({one: 'I have one apple.', other: 'I have {0} apples.', 2, 2),
};
}
Note:
The count
parameter is not part of the displayed values. To have the number
count
displayed, one must add this parameter to the list of values.
Examples:
// With english locale
__n({one: 'I have one cat.', other: 'I have not one cat.'}, 0)
=>
'I have not one cat.'
// With french locale
// Note that the parameter 0 is put two times:
// The first one is used as the count parameter and the second is displayed as
// first value ({0}).
__n({one: "J'ai {0} chat.", other: "J'ai {0} chats."}, 0, 0)
=>
"J'ai 0 chat."
// If the targeted plural is not found (here 'one'), 'other' is selected.
__n({other: '{a} {a} {b} {b} {b}'}, 1, {a: 'foo', b: 'bar'})
=>
'foo foo bar bar bar'
Russian json file (from i18n example):
{
"cat_key": {
"one": "%d кошка",
"few": "%d кошки",
"many": "%d кошек",
"other": "%d кошка",
}
}
Use:
__n('cat_key', 0, 0);
=>
'0 кошек'
__n('cat_key', 1, 1);
=>
'1 кошка'
__n('cat_key', 2, 2);
=>
'2 кошки'
__n('cat_key', 5, 5);
=>
'5 кошек'
__n('cat_key', 6, 6);
=>
'6 кошек'
__n('cat_key', 21, 21);
=>
'21 кошка'
Get locale from query / cookie and header.
Set locale and cookie.
Where does locale come from, could be query
, cookie
, header
and default
.
Get the given locale text on application level.
console.log(app.__('zh', 'Hello'));
// stdout '你好' for Chinese
this.state.__ = this.__.bind(this);
Nunjucks example:
{{ __('Hello, %s', user.name) }}
Pug example:
p= __('Hello, %s', user.name)
Koa-pug integration:
You can set the property locals on the KoaPug instance, where the default locals are stored.
app.use(async (ctx, next) => {
koaPug.locals.__ = ctx.__.bind(ctx);
await next();
});
Get the given locale text with plural management on application level.
console.log(app.__n('zh', {other: 'Hello'}, 0));
// stdout '你好' for Chinese
this.state.__n = this.__n.bind(this);
Nunjucks example:
{{ __n({other: 'Hello, %s'}, 2, user.name) }}
Pug example:
p= __n({other: 'Hello, %s'}, 2, user.name)
Koa-pug integration:
You can set the property locals on the KoaPug instance, where the default locals are stored.
app.use(async (ctx, next) => {
koaPug.locals.__n = ctx.__n.bind(ctx);
await next();
});
If you are interested on knowing what locale was chosen and why you can enable the debug messages from debug.
There is two level of verbosity:
$ DEBUG=koa-locales node .
With this line it only will show one line per request, with the chosen language and the origin where the locale come from (queryString, header or cookie).
$ DEBUG=koa-locales:silly node .
Use this level if something doesn't work as you expect. This is going to debug everything, including each translated line of text.