检测到语言但翻译不适用于 i18n
Language getting detected but translation not working with i18n
我已经在我的 Express Node js 服务器中设置了 i18n 中间件,如下所示:
// server.js
import i18nMiddleware from 'i18next-express-middleware';
import i18n from 'i18next';
import Backend from 'i18next-node-fs-backend';
import { LanguageDetector } from 'i18next-express-middleware';
i18n
.use(Backend)
.use(LanguageDetector)
.init({
whitelist: ['en', 'my'],
fallbackLng: 'en',
// have a common namespace used around the full app
ns: ['common'],
defaultNS: 'common',
debug: false,
backend: {
loadPath: './locales/{{lng}}/{{ns}}.json',
// jsonIndent: 2
}
});
app.use(i18nMiddleware.handle(i18n))
这是翻译测试文件:
// test.js
import i18next from "i18next";
const test = (req, res) =>{
const t = req.i18n.t.bind(i18next);
console.log(req.i18n.language) // language set correctly :)
console.log(t('title')) // translation not working :(
}
title 在英文中的值为 title,在马来语中为 tajuk
As per the express middleware documentation,我将 my 作为 accept-language header 传递,并且 console.log(req.i18n.language)
正确打印它.
但是,console.log(t('title'))
仍在打印 title 而不是 tajuk
这看起来很疯狂,但这解决了问题:
const i18n = req.i18n;
console.log(i18n.t('title'))
我已经在我的 Express Node js 服务器中设置了 i18n 中间件,如下所示:
// server.js
import i18nMiddleware from 'i18next-express-middleware';
import i18n from 'i18next';
import Backend from 'i18next-node-fs-backend';
import { LanguageDetector } from 'i18next-express-middleware';
i18n
.use(Backend)
.use(LanguageDetector)
.init({
whitelist: ['en', 'my'],
fallbackLng: 'en',
// have a common namespace used around the full app
ns: ['common'],
defaultNS: 'common',
debug: false,
backend: {
loadPath: './locales/{{lng}}/{{ns}}.json',
// jsonIndent: 2
}
});
app.use(i18nMiddleware.handle(i18n))
这是翻译测试文件:
// test.js
import i18next from "i18next";
const test = (req, res) =>{
const t = req.i18n.t.bind(i18next);
console.log(req.i18n.language) // language set correctly :)
console.log(t('title')) // translation not working :(
}
title 在英文中的值为 title,在马来语中为 tajuk
As per the express middleware documentation,我将 my 作为 accept-language header 传递,并且 console.log(req.i18n.language)
正确打印它.
但是,console.log(t('title'))
仍在打印 title 而不是 tajuk
这看起来很疯狂,但这解决了问题:
const i18n = req.i18n;
console.log(i18n.t('title'))