Tạo site đa ngôn ngữ expressjs với i18n
Bước 1: Cài thư viện
var i18n = require("i18n");
Bước 2: trong file app.js thêm code sau:
//==== language
app.use(i18n.init);
i18n.configure({
locales:['en', 'vi'],
directory: __dirname + '/locales',
cookie: 'lang',
});
app.use('/', (req, res, next) => {
if( req.query.hl != null)
{
res.cookie('lang', req.query.hl, { maxAge: 900000 });
res.redirect('back');
}
next();
});
Bước 3: Tạo thư mục locales và tạo file en.json , vi.json
//code en.json
{
"Home" : "Home",
"My Account": "My Account",
"Shopping Cart": "My Account",
"CheckOut" : "My Account"
}
// code vi.json
{
"Home" : "Trang chủ",
"My Account": "Tài khoản",
"Shopping Cart": "Giỏ hàng",
"CheckOut" : "Thanh toán"
}
Bước 4: Trong view ejs dùng lệnh hiển thị
<%= __('Home') %>
Bước 5: chạy thử với các địa chỉ:
/?hl=en
/?hl=vi
Nguồn: zezo.dev