This package has been deprecated

Author message:

package not maintained; will not be maintained in future

mlang

1.0.6 • Public • Published

mlang

Simple localization middleware for Express (and the like).

Example usage with Express

var app = require('express')();
var mlang = require('mlang');

app.use(mlang({
    languages: ['en', 'de', 'it', 'fr'],
    path: './locale',
    cookie: 'lang'
}));

app.get('/', function(req, res){
    res.send(res.locals._('message.hello');
});

API

Configuration

The mlang function call accepts an object with several configuration options.

string path

Path to the language files.

  • default ''

array[string] languages

All available languages.

  • default []
  • when autoDetect is allowed, mlang will attempt to match the langugaes in the order they are entered.

string defaultLanguage

Default language.

  • default 'en'
  • language to use when no other match was found

bool autoDetect

Detect language automatically from headers.

  • default true

string|bool cookie

Cookie name to read language from.

  • default false
  • uses express-cookie if present, otherwise attempts to parse directly from headers
  • has higher priority than autoDetect
  • empty or false if cookies shouldn't be used

string ns

"Namespace" to use when appending to res.locals.

  • default ''
  • will append to res.locals.ns instead of directly res.locals

Language files

Every language file is a basic Node.js module that exports an object. The file name must be the same as the language code.

module.exports = {
    message: {
        hello: 'Hello World',
        welcome: 'Welcome %s, dear %s'
    }
};

Using localized text in templates (with Pug examples)

mlang uses plain objects, allowing you to access all localized text directly using normal object notation. In addition to that, mlang adds a special _ function on each object.

Direct access

h1= message.hello

Using _ function

h1= _('message.hello')

The added benefit of using _ function is that you can pass additional arguments in sprintf style that will be replaced into the string.

_ with additional arguments

// message.welcome = "Welcome %s, dear %s"
h1= _('message.welcome', 'to my site', 'John') // will output "Welcome to my site, dear John"

_lang

mlang also appends the language code to _lang property if it doesn't exist already. This can be used inside HTML lang attributes, for example.

Motivation

I wanted a simple localization package for my new Node.js project, and while there are already very powerful packages for this, they felt way too much for my simpler, more basic, needs (I'm aware there are even simpler ones) and so I decided to try it out and built my own.

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Published

Version History

  • Version
    Downloads (Last 7 Days)
    • Published

Package Sidebar

Install

npm i mlang

Weekly Downloads

0

Version

1.0.6

License

MIT

Last publish

Collaborators

  • roal