| 
				
					 | 
			2 gadi atpakaļ | |
|---|---|---|
| .. | ||
| node_modules | 2 gadi atpakaļ | |
| History.md | 2 gadi atpakaļ | |
| LICENSE | 2 gadi atpakaļ | |
| README.md | 2 gadi atpakaļ | |
| index.js | 2 gadi atpakaļ | |
| package.json | 2 gadi atpakaļ | |
koa locales, i18n solution for koa:
options.dirs.*.js, *.json and *.properties, see examples.__(key[, value, ...]).query, cookie and header: 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);
locales(app, options)Patch locales functions to koa app.
__.['$PWD/locales'].en-US.locale.locale.''.{}.1y, expired after one year.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,
  },
});
context.__(key[, value1[, value2, ...]])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'
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.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();
});
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.