Home

Awesome

think-i18n

Build Status Coverage Status npm

简体中文文档

i18n solution in thinkjs 3.0, implement base on Jed, Moment and Numeral.

Features

How to Use

npm install think-i18n --save

Configure extends.js

// thinkjs config/extend.js

const createI18n = require('think-i18n');
const path = require('path');

module.exports = [
  createI18n({
    i18nFolder: path.resolve(__dirname, '../i18n'),
    localesMapping(locales) {return 'en';}

  })
];

complete options

Locale Settings

Each locale settings is a javascript file. see example

module.exports = {
    app: think.app, // if not passed in, __ will not be auto `assign` into `think-view` instance
    localeId,
    translation,
    dateFormat, // optional
    numeralFormat, // optional
}

Controller and View (nunjucks)

Controller

You can get i18n instance or current locale in controller.


    async indexAction(){
      this.assign(this.i18n(/*forceLocale*/));
      ...
    }

View

If you used think-view , think-i18n will auto-inject an i18n instance into __ field, like this.assign('__', this.getI18n()).


{{ __('some key') }} translation
{{ __.jed.dgettext('domain', 'some key') }} translation in specify domain
{{ __.moment().format('llll') }} datetime format
{{ __.numeral(1000).format('currency') }} number format (see numberFormat.formats)

Complete Options

   Object.assign(jedOptions, {locale_data: <your locale translation>})

Some Thoughs Behine

Why combine all there libraries' i18n config into one? the answer is for transparent but most importantly, flexibility to compose you date, number and message's behavior per locale, for example, you have a website in China and want to provide English translation, but keep the chinese currency symbol, so you can compose english translation and chinese date and currency in your en.js locale setting.

// locale setting of en.js
module.exports = {
  localeId: 'en_ch',
  translation: require('../english.po.json'),
  dateFormat: require('../moment/en.json'),
  numeralFormat: require('../numeral/en.json')
};

We should always use customize format.

Notice