Internationalization and localization With Express JS Application - PART B

In Part A building express js application is done now add language support with Express JS application.

for multiple language support requied "i18n" NPM module.

Install i18n npm module

    
    npm install i18n --save

Now Add i18n configuration in app.js in express js application


var i18n = require('i18n');

i18n.configure({
    locales: ['en', 'ma'],
    defaultLocale: 'ma',
    directory: __dirname + '/locales'
});

locales: ['en', 'ma'] is locales array , here you can add multile locales which support your application.

defaultLocale: 'ma'

you can also set default locale value using defaultLocale key in configuration.

Now where is all local value located.

In application directory create one folder with name locales or any custome name.
and create all locale JSON file in that folder.

localesfolder

now my en.json and mr.json looking with following format with values.

en.json

    {
        "Hello": "Hello Welcome "
    }

mr.json

    {
        "Hello": "नमस्कार स्वागत आहे",
    }

Now application level inti i18n

    app.use(i18n.init);
 

Now in front-end side adding one from with drop to select langugae

<form action="/" method="post">
    <select name="language">
        <option value="mr">Marathi</option>
        <option value="en">English</option>
    </select>
    <input type="submit" value="Submit" name="submit">
</form>
<h1><%= title %></h1>


And in route file use following code , here we are user index.js

var express = require('express');
var router = express.Router();
var i18n = require('i18n');

Above code snipet adding 'i18n';


/* GET home page. */
router.get('/', function (req, res, next) {

    res.render('index', {
        title: res.__('Hello'),
        lang: i18n.getLocale(req)
    });

});

Here index.ejs load from index route with default loacale.


router.post('/', function (req, res, next) {

    req.app.set('lang', req.body.language);

    i18n.setLocale(res, req.app.get('lang'));

    res.render('index', {
        title: res.__('Hello'),
        lang: i18n.getLocale(req)
    });
});

module.exports = router;

After selecting language from index.ejs send post request to index.js route file.
and in index.js file set user selected local or language