Lingua
Lingua is a middleware for the Express.js framework that helps you to internationalise your webapp easily. It determines the language of the user agent and pushes the i18n resources to your views.
Installation
$ npm install lingua
Quick Start
Using lingua comes down with four simple steps:
-
Grab lingua
var express =lingua = ;...// Express init code goes here...// Express app configuration code and lingua init.app;Note: Please ensure that the call: "app.use(app.router);" is the last entry in your configuration section.
-
Create i18n resource files - Note that you have to create a resource file for your default language. (In this example: './i18n/en.json' and './i18n/de-de.json').
// en.json"title": "Hello World""content":"description": "A little description."// de-de.json"title": "Hallo Welt""content":"description": "Eine kleine Beschreibung." -
a. Use lingua in your views - Static output - Note that the syntax depends on your template engine. In this example it is: ejs and the request comes from a browser which sends 'en' with the HTTP request header.
<%= lingua.title %> <!-- out: <h1>Hello World</h1> --><%= lingua.content.description %> <!-- out: <p>A little description.</p> -->b. Use lingua in your views - Dynamic output - Sometimes it is necessary to handle dynamic data within your express route and pass it to the template. What if your i18n resource includes placeholders ("{key}") within a string where you can put in your dynamic data? Well, it is possible. First of all, look at this i18n resource file:
// de.json"greeting": "Hallo {name}. Dieser Schlüssel {code} wurde für Dich generiert."Now it is possible to transfer an object from your route into your template:
app;And finally you can execute the i18n resource (yes, you can execute it (: ) and pass your data model to this function:
<%= lingua.greeting(person) %>Note: Every i18n resource which contains placeholders like in the example above is a function after you've started the application.
-
Let the user select a language - Note that the user's selection is persisted within a cookie. This is an optional step. If you want to let lingua determine the user language from the browser configuration then leave this step out. Anyway, this is a very handy feature for switching the language by a user decision.
de-DEen-USYou can configure lingua in order to change the name of this parameter.
// Express app configuration code and lingua init.app;The cookie lingua uses expires in one year, and includes the httpOnly flag to prevent clientside access from Javascript. You can override these settings by providing a cookieOptions key during configuration.
// Express app configuration code and lingua init.app;
Example Application
There is an example application at ./example
To run it:
$ cd example
$ node app.js
You can find a deployed version of this app here.
License
Author
Copyright (c) 2013, André König