【问题标题】:Set i18next language based on HTML tag根据 HTML 标签设置 i18next 语言
【发布时间】:2020-09-16 04:24:23
【问题描述】:

好的,所以我正在试验 ReactJS 和 i18next。

我想根据初始页面加载设置我的翻译语言 一些html标签。

例如,如果我在页面加载时有<html lang="de">,我想拥有 在进行任何翻译之前,lng 设置为 de

这是我的i18n.js 文件的内容:

import i18n from "i18next";
import { initReactI18next } from "react-i18next";

// the translations
// (tip move them in a JSON file and import them)
const resources = {
  en: {
    translation: {
      "Welcome to React": "Translation in English"
    }
  },
  de: {
    translation: {
      "Welcome to React": "Translation in German"
    }
  }
};

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources,
    lng: "en",

    keySeparator: false, // we do not use keys in form messages.welcome

    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

  export default i18n;

【问题讨论】:

    标签: reactjs i18next react-i18next


    【解决方案1】:

    来自here

    const htmlLang = document.documentElement.lang; // for <html lang=".."> not xml-lang:".."
    

    现在你可以把这个常量放在你的 i18n 声明中

    i18n
      .use(initReactI18next) // passes i18n down to react-i18next
      .init({
        resources,
        lng: htmlLang,
    
        keySeparator: false, // we do not use keys in form messages.welcome
    
        interpolation: {
          escapeValue: false // react already safes from xss
        },
        fallbackLng: ['en', //'fr', ...]
      });
    

    我还添加了一种备用语言

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 1970-01-01
      • 2021-01-31
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      相关资源
      最近更新 更多