koa-adam-locale
Simple Multi Language Middleware for Koa.
Installation
$ npm install koa-adam-locale
Example
app.js:
var Path = ;var View = var KAL = ;var koa = ;var app = ; /* i18n */app; /* templating */app; app app
i18n/en_US.json
views/locale.ejs
<%= _i18n_.hello %>, <%= _i18n_.world %>.current:<%= _i18n_current_ %>.<% for(var i in _i18n_supported_) { %> switch to <%= _i18n_supported_[i].lang %><% } %>
Options
path {String}
The folder path of i18n files
reference {Object}
The reference of i18n Object, key of this reference should match the code, like 'zh_CN', 'en_US' (Case sensitive),
and this parameter has a higher priority than path
.
supported {Array}
The supported languages. default value: [{code:'en_US', lang:'English'},{code:'zh_CN', lang:'简体中文'}]
Example:
app;
namespace {String}
Custom template data params namespace. Default value is 'locals'
- koa-views 2.x - ctx.locals
- koa-views 3.x - ctx.state
Example:
// for koa-views 3.xapp;
cookieKey {String}
cookies {Object}
Store the selected language in the cookie. see koa cookie for more information.
Example:
app;
default {String}
Default language
Example:
app;
set_url {String}
The url to switch current language. default value: /set_locale
Example:
app;
Then you can set current language by request url like this '/set_locale?lang=en_US'
Local Params
The following three params are set to ctx.namespace, default ctx.locals
. For koa-views 3.x version, you can set namespace to ctx.state
this.locals._i18n_
{Object}this.locals._i18n_current_
{String}this.locals._i18n_supported_
{Array}
static addLanguageHelper
添加dust模板的helper,用于展示语言名称
var dust = require('dustjs-helpers');
KAL.addLanguageHelper(dust)
在模板里使用@language
{@language code="ru_RU" current="zh_CN" /} // 输出"俄语"
{@language code="ru_RU" current="en_US" /} // 输出"Russian"
{@language code="ru_RU" /} // 根据系统设置的自动判断语言
Debug
Set the DEBUG
environment variable to koa-adam-locale
when starting your server.
$ DEBUG=koa-adam-locale
License
MIT