Reputation: 4991
I'm using Expressjs and i18n for my node js application to manage the multilanguage.
Here is my i18n configuration :
i18n.js
var i18n = require('i18n');
i18n.configure({
locales:['en', 'fr'],
directory: __dirname + '/../locales',
defaultLocale: 'en',
cookie: 'lang',
});
module.exports = function(req, res, next) {
i18n.init(req, res);
res.locals.__= res.__;
var current_locale = i18n.getLocale();
return next();
};
server.js
var i18n = require('./configs/i18n');
...
app.use(i18n);
Actually if I want to change the locale settings I have to do that for each routes :
app.get('/index', function(req, res){
res.setLocale('fr')
res.render('pages/index');
});
It is possible to use setLocale()
once and it will permanently change the locale ?
And what is the best practice ? Should I specify the language inside my routes everytime ? E.g :
app.get('/:locale/index', function(req, res){
res.setLocale(req.params.locale)
res.render('pages/index');
});
app.get('/:locale/anotherroute', function(req, res){
res.setLocale(req.params.locale)
res.render('pages/anotherroute');
});
Or I have to store the locale in my database for each user ?
Upvotes: 0
Views: 5884
Reputation: 889
You can use middlewares to avoid the repetition (place this code before your router) :
// Fixed locale
app.use(function (req, res, next) {
res.setLocale('fr');
next();
});
// Locale get by URL parameters
app.use(function (req, res, next) {
if (req.params && req.params.locale){
res.setLocale(req.params.locale);
}
next();
});
Personally, I prefer to store the local setting in database, it avoids to weighing the request with not necessary data.
Another solution is to set the language with HTTP headers Content-Language
and Accept-Language
and get it with req.acceptsLanguage()
.
Upvotes: 2