I have included i18next in my Express application and configured it as follows:
const i18next = require('i18next');
const Backend = require('i18next-fs-backend');
const i18nextMiddleware = require('i18next-http-middleware');
i18next
.use(Backend)
.use(i18nextMiddleware.LanguageDetector)
.init({
backend: {
loadPath: __dirname '/locales/{{lng}}/{{ns}}.json'
},
fallbackLng: 'en',
preload: ['en', 'de']
});
The paths for my translation files are correct, and look like this:
locales/de/translation.json
{
"SignIn": "Anmelden",
"Username": "Benutzername",
"Password": "Passwort",
"Login": "Anmelden"
}
locales/en/translation.json
{
"SignIn": "Sign in",
"Username": "Username",
"Password": "Password",
"Login": "Login"
}
When rendering the ejs template, I pass the t function of i18next to the view like this
res.render("index",{t:i18next.t});
In the template, I then use the value as follows:
<h2 class="ui center aligned header"><%= t("SignIn") %></h2>
The result is that nothing is displayed at all, neither the fallback language nor German, since my browser is German and the Language Detector should detect that.
I read that you have to rebind the t functions to make it work in the view, I tried that as well, like this:
res.render("index", {t: i18next.t.bind(i18next.t)});
As soon as I do that, the fallback language is rendered, if I change it to German, German is rendered as well.
But the language is not detected automatically
CodePudding user response:
It looks like the t
function is already available for the templates via http-middleware
, without explicitly passing an object from the backend.
So far, it seems everything work fine.