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
const koa = ;const locales = ; const app = ;const options = dirs: __dirname + '/locales' __dirname + '/foo/locales';;
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
. - {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
;
Aliases
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.
;
context.__(key[, value1[, value2, ...]])
Get current request locale text.
{ ctxbody = message: ctx ;}
Examples:
'Hello fengmk2. koa rock!' 'foo foo bar bar bar' 'foo foo bar bar bar'
context.__getLocale()
Get locale from query / cookie and header.
context.setLocale()
Set locale and cookie.
context.__getLocaleOrigin()
Where does locale come from, could be query
, cookie
, header
and default
.
app.__(locale, key[, value1[, value2, ...]])
Get the given locale text on application level.
console;// stdout '你好' for Chinese
Usage on template
thisstate__ = 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;
Debugging
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.