Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain changing state of language in expressJS

I`m working on a project using nodeJs, handlebars and expressJs framework. I add change language functionality using i18n-express module.This module add query string in the end of url when we are going to change the language. Now the issue is that when i have move one page to another page then query string is removed and lose his state.so how can i maintain state of language?? if user choose french language then all pages are open in french. This is what i want.

Code:

var i18n =  require("i18n-express");

app.use(i18n({
  translationsPath: path.join(__dirname, 'lang'), // <--- use here. Specify translations files path.
  siteLangs: ["ar","en","cn","fr","ge","he","hu","it","ja","ko","es","ru"],
  cookieLangName : 'ulang',
  textsVarName: 'translation'  
}));

Link to change the language

<a href="#!" id="{{icon}}" onclick=" return changeLanguage(this)"></a>

Onclick function to change the language

function changeLanguage(event){
   $('#languages img').attr('src','/images/flag-icons/'+event.id+'.png');
   var url = window.location.href;
   url = url.split("?")[0];
   url += '?clang='+event.id;
   window.location.href = url;
   localStorage.setItem("clang", '?clang='+event.id); //event.id returns locale name such as en, ar, sp, fr etc.
   //console.log(url);
}
like image 227
Varinder Sohal Avatar asked Oct 11 '18 06:10

Varinder Sohal


People also ask

Is ExpressJS still maintained?

It is unmaintained Express has not been updated for years, and its next version has been in alpha for 6 years. People may think it is not updated because the API is stable and does not need change.

What is the alternative of ExpressJS?

Koa, React, Flask, Django, and Golang are the most popular alternatives and competitors to ExpressJS.


3 Answers

I recommend you Lingua for ExpressJS

Basically, Lingua is a middleware for the Express.js and that helps you to internationalise your webapp easily. It determines the language of the user agent and pushes the i18n resources to your views.

$ npm install -s lingua

var express = require('express'),
    lingua  = require('lingua');

// Express app configuration code and lingua init.
app.configure(function() {

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

// Lingua configuration
app.use(lingua(app, {
    defaultLocale: 'en',
    path: __dirname + '/i18n'
}));

app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/public'));
app.use(app.router);

Language files

'./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."
        }
    }

And you can easily implement it on your pages with:

<h1><%= lingua.title %></h1> <!-- out: <h1>Hello World</h1> -->
<p><%= lingua.content.description %></h1> <!-- out: <p>A little description.</p> -->
like image 197
Benjamin RD Avatar answered Oct 21 '22 02:10

Benjamin RD


On clientside if you are able to set an item on local storage then you are also able to get the same item and use its value to push it to the querystring as well. So you basically need an additional function on your client javascript that will get the item everytime the page opens.

    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    function checkLanguageFromLocalStorage(){
        var clang = getParameterByName('clang');
        if (clang == null) {
            if (localStorage.getItem("clang") != null) {
                var clang = localStorage.getItem("clang");
                var url = window.location.href;
                url = url.split("?")[0];
                url += '?clang='+clang;
                window.location.href = url;
            }
        }
    }

    checkLanguageFromLocalStorage();
like image 21
Gianpaolo Papa Avatar answered Oct 21 '22 04:10

Gianpaolo Papa


Why don't you pass a cookie with the language instead of query parameter? i18n-express has an option called cookieLangName which you have allready configured on the server side (cookieLangName: 'ulang'). Setting cookieLangName makes i18n-express read language from the cookie with the name you pass. All you need is to set this cookie in you client side script - inside changeLanguage function - and it will do the trick:

function changeLanguage(event){
   $('#languages img').attr('src','/images/flag-icons/'+event.id+'.png');
   document.cookie = `ulang=${event.id}; path=/`;

   localStorage.setItem("ulang", `ulang=${event.id}; path=/`); // you can still save it to localStorage and synchronize it when cookie is removed
}
like image 1
Volodymyr Avatar answered Oct 21 '22 04:10

Volodymyr