【问题标题】:i18next react & express access the key without writing the lang code and the translation keyi18next react & express 访问密钥,无需编写语言代码和翻译密钥
【发布时间】:2022-02-11 03:47:49
【问题描述】:

您好,我试图在我的应用程序中支持多语言,但我必须通过从 express 获得的响应来访问密钥。 我在 react 和 express 中使用 i18n 从后端获取翻译。 就像这对我有用:

t('en.translation.user')

但我想这样做:

t('user')

这是我在客户端中的代码:

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import Backend from "i18next-http-backend";

i18n
    .use(Backend)
    .use(initReactI18next)
    .init({
        lng: "en",
        fallbackLng: "en",
        backend: {
                loadPath: "http://localhost:4000/locales/resources.json?lng={{lng}}&ns={{ns}}",
                addPath: "http://localhost:4000/locales/add/{{lng}}/{{ns}}",
                allowMultiLoading: false,
        },
        interpolation: {
            escapeValue: false, // react already safes from xss
        },

    });
export default i18n;

我的服务器是这样的:

const i18next = require('i18next');
const Backend = require('i18next-node-fs-backend');
const i18nextMiddleware = require('i18next-express-middleware');

const pathTranslationPublic = path.join(__dirname, '/src/locales');
i18next.use(Backend).init({
    preload: ['en',],
    lowerCaseLng: true,
    backend: {
        loadPath: `${pathTranslationPublic}/{{lng}}/{{ns}}.json`,
        addPath: `${pathTranslationPublic}/{{lng}}/{{ns}}.missing.json`,
        jsonIndent: 4,
    },
    load: 'all',
    lng: 'en',
    fallbackLng: 'en',
    debug: true,
    saveMissing: true,
    formatSeparator:'.'
});
app.use(
    i18nextMiddleware.handle(i18next, {
        removeLngFromUrl: false,
    }),
);
app.get(
    '/locales/resources.json',
    i18nextMiddleware.getResourcesHandler(i18next),
);

这是来自客户端的响应:

{
    "en": {
        "translation": {
            "user": "hello user"
        }
    }
}

【问题讨论】:

    标签: node.js reactjs i18next react-i18next i18next-http-backend


    【解决方案1】:

    getResourcesHandler 用于多重加载...

    要将翻译提供给您的反应客户端,只需静态提供它们,即

    app.use(express.static(pathTranslationPublic));
    

    这样客户端可以有一个类似'/{{lng}}/{{ns}}.json'的loadPath

    顺便说一句: i18next-node-fs-backend 已弃用,请改用i18next-fs-backend i18next-express-middleware 已弃用,请改用i18next-http-middleware

    有关 i18next 的反应指南,请查看:https://dev.to/adrai/how-to-properly-internationalize-a-react-application-using-i18next-3hdb

    【讨论】:

    • 好的,谢谢。但我的问题是客户需要语言的密钥和翻译的密钥,之后我需要编写我想要的正确密钥。如果我还有另一种语言:t('en.translation.user') 不起作用。
    • 静态提供翻译时,如 app.use(express.static(pathTranslationPublic));客户端可以这样做:t('user')
    猜你喜欢
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 2018-01-26
    • 2019-12-07
    相关资源
    最近更新 更多