Giter Club home page Giter Club logo

locales's Introduction

koa-locales

NPM version build status Test coverage David deps npm download

koa locales, i18n solution for koa:

  1. All locales resources location on options.dirs.
  2. resources file supports: *.js, *.json, *.yml, *.yaml and *.properties, see examples.
  3. One api: __(key[, value, ...]).
  4. Auto detect request locale from query, cookie and header: Accept-Language.

Installation

$ npm install koa-locales --save

Quick start

const koa = require('koa');
const locales = require('koa-locales');

const app = koa();
const 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.
    • {String} cookieDomain: domain on cookie. Optional, default is ''.
    • {Object} localeAlias: locale value map. Optional, default is {}.
    • {Boolean} writeCookie: set cookie if header not sent. Optional, default is true.
    • {String|Number} cookieMaxAge: set locale cookie value max age. Optional, default is 1y, expired after one year.
locales({
  app: app,
  dirs: [__dirname + '/app/locales'],
  defaultLocale: 'zh-CN',
});

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.

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

Usage on template

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();
});

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.

License

MIT

locales's People

Contributors

alijs avatar dead-horse avatar desaroger avatar fengmk2 avatar greenkeeperio-bot avatar harbin1053020115 avatar hotoo avatar huacnlee avatar monkindey avatar niftylettuce avatar popomore avatar tallcode avatar tonystreet avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

locales's Issues

How to merge locales after startup

Suggest to provide a function to update/merge locales, since in my case, languages are stored in database, and may be updated online.

localeAlias is broken

I'm trying to make this work:

   locales(app, {
      defaultLocale: 'en',
      localeAlias: {
         es: 'es_AR',
         en: 'en_US',
      }
   });

Whatever I send in "Accept-Language" header parameter: "es", "es_AR" or "en_US" always loads the defaultLocale language, only when I completely remove localeAlias setting then I can set "es" in the header and the language changes otherwise I'm stuck with defaultLocale

It seems to be totally broken. Also what happens if I want 2 aliases for "es"?, since it's not possible to repeat keys in an object, maybe I should invert key values but that doesn't work and it's not how it's documented in the readme.

any plans to support loading locales from database?

I have 5+ different projects and I don't want to copy existing translations or pay to have them retranslated. Looking for ways to share locale translated text across projects and it seems database storage is how others have done it in rails land. What do you think for Koa?

some startup errors

after installing koa-locales, I got the error message "Cannot find module 'merge-descriptors'".
Then I manually moved "merge-descriptors" from devDependencies to dependencies, and after hitting npm install in that folder "node_modules/koa-locales/" I get this:

.../node_modules/koa-locales/index.js:98
  app.context[functionName] = function (key, value) {

TypeError: Cannot set property '__' of undefined

I am stuck.

Code from the readme doesn't work

In the readme this code is provided:

locales({
  app: app,
  dirs: [__dirname + '/app/locales'],
  defaultLocale: 'zh-CN',
});

And throws this error:
TypeError: Cannot set property '__' of undefined

Only passing app as a parameter works like this:

locales(app, {
  dirs: [__dirname + '/app/locales'],
  defaultLocale: 'zh-CN',
});

So documentation should be fixed

remove "merge-descriptors" dependency at all?

Hi -

this time no bug, only an idea:
Since there is Node v4.0 out, would it make sense to replace the line

merge(resources[locale], resource);

in index.js, line 62 with

Object.assign(resources[locale], resource);

?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.