2016-08-09 33 views
0

我正在使用Expressjs和i18n爲我的節點js應用程序管理多語言。節點js永久性本地化更改

這裏是我的國際化配置:

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); 

其實如果我想改變區域設置我有爲每條路線做這件事:

app.get('/index', function(req, res){ 
    res.setLocale('fr') 

    res.render('pages/index'); 
}); 

可以使用setLocale()一次,它會永久更改區域設置?

什麼是最佳實踐?我應該每次在我的路線中指定語言嗎?例如:

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'); 
}); 

或者我必須在每個用戶的數據庫中存儲區域設置?

回答

1

您可以使用middlewares避免重複(將此代碼路由器前):

// 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(); 
}); 

就個人而言,我更喜歡存儲在數據庫中的本地設置,它避免了稱重與沒有必要的數據的請求。

另一種解決方案是設置與HTTP頭Content-LanguageAccept-Language的語言和req.acceptsLanguage()得到它。

+0

謝謝你的回答。我得到不能讀取未定義的屬性'locale'?這意味着我應該爲每個路由指定locale參數嗎?'app.get('/:locale/index',function(req,res)' – John

+0

我更新了這篇文章,我修復了這個錯誤,並添加了一個更好的解決方案基於HTTP頭和函數acceptLanguage()函數,我希望它能夠解決你的問題 –

+1

好的,謝謝,所以如果我想在我的數據庫中存儲語言,我只需要在你的固定語言環境中執行mongoDB查詢或者用我的passportJS用戶會話變量獲得它嗎? – John