koa-locales2
v1.6.0
Published
koa locales, i18n solution for koa
Downloads
6
Maintainers
Readme
koa-locales
koa locales, i18n solution for koa:
- All locales resources location on
options.dirs
. - resources file supports:
*.js
,*.json
and*.properties
, see examples. - One api:
__(key[, value, ...])
. - Auto detect request locale from
query
,cookie
andheader: Accept-Language
.
Installation
$ npm install koa-locales --save
Quick start
var koa = require('koa');
var locales = require('koa-locales');
var app = koa();
var options = {
dirs: [__dirname + '/locales', __dirname + '/foo/locales'],
};
locales(app, options);
API Reference
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} 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
. - {Object} localeAlias: locale cookie 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',
}));
context.__(key[, value1[, value2, ...]])
Get current request locale text.
function* home() {
this.body = {
message: this.__('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'
Usage on template
this.state.__ = this.__.bind(this);
nunjucks example:
{{ __('Hello, %s', user.name) }}