I’m new to Node JS, I have problem with it using localization i18n for Node JS and express also I’m using ejs as my view engine..
My locals files like this:
en.json
{
"test": "this is a test",
}
fr.json
{
"test": "c'est un test",
}
My server.js simply like this:
const express = require('express');
const app = express();
const i18n = require('i18n');
i18n.configure({
locales: ['en', 'fr'],
directory: __dirname + '/locales',
defaultLocale: 'en',
cookie: 'lang',
});
app.use(i18n.init);
app.set('view engine', 'ejs');
app.get('/', (req, res, next) => {
res.render('index');
});
app.listen(3000);
My index.ejs is:
<!DOCTYPE html>
<html lang="<%= res.locale %>">
<head>
<meta charset="UTF-8">
<title>Test App</title>
</head>
<body>
<h1><%= res.__('test') %></h1>
</body>
</html>
Finally, my express server is properly running without localization.
Now after setting it up for localization and running it again I got those errors!
- res is not defined in
<html lang="<%= res.locale %>"> - res is not defined in
<h1><%= res.__('test') %></h1>
If I try to remove the res. it’s working however the language is not changing!
So how to rectify this problem and how can I hardcode shifting between the langauges like by changing defaultLocale: 'fr' or i18n.setLocale('fr') ?