从数据库获取语言环境而不是浏览器的i18next

4

我目前从用户的浏览器中获取区域设置。现在,用户可以在其个人资料中设置其首选语言,这将存储在数据库中。我想从数据库中获取此值并为i18next设置正确的区域设置。我在这里阅读了有关自己检测功能的一些内容:https://github.com/i18next/i18next-browser-languageDetector。但我不确定是否应该使用它。我的文件当前设置如下:

import i18n from 'i18next';
import Backend from 'i18next-xhr-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
import { reactI18nextModule } from 'react-i18next';
import moment from 'moment';

export const i18nInit = (callback = () => { }) =>
  // for easy overview use: https://devhints.io/moment its better than official docs:
  moment.defineLocale('nl-custom', {
    parentLocale: 'nl',
    longDateFormat: {
      LT: 'HH:mm',
      LTS: 'HH:mm:ss',
      L: 'D MMM', // need this format to display dates in past year(s)
      LL: 'D MMMM YYYY', // need this format to display dates in the current year
      LLL: 'YYYY-MM-DD HH:mm', // need this format as input for the date picker
      LLLL: 'dddd D MMMM YYYY HH:mm',
    },
  }) &&
  moment.defineLocale('en-custom', {
    parentLocale: 'en',
    longDateFormat: {
      LT: 'HH:mm',
      LTS: 'HH:mm:ss',
      L: 'MMM D',
      LL: 'MMMM D YYYY', // need this format to display dates in the current year
      LLL: 'YYYY-MM-DD HH:mm', // need this format as input for the date picker
      LLLL: 'MMMM dddd D YYYY HH:mm',
    },
  }) &&
  i18n
    // load translation using xhr -> see /public/locales
    // learn more: https://github.com/i18next/i18next-xhr-backend
    .use(Backend)
    // detect user language
    // learn more: https://github.com/i18next/i18next-browser-languageDetector
    .use(LanguageDetector)
    // pass the i18n instance to the react-i18next components.
    // Alternative use the I18nextProvider: https://react.i18next.com/components/i18nextprovider
    .use(reactI18nextModule)
    // init i18next
    // for all options read: https://www.i18next.com/overview/configuration-options
    .init(
      {
        fallbackLng: 'en',
        ns: ['actionpoints', 'common', 'menu', 'messages', 'overview', 'settings', 'shepherdTour', 'users', 'profile', 'meetingtypes'],
        defaultNS: 'common',
        whitelist: ['nl', 'en'],
        backend: {
          // Path where resources get loaded from, or a function
          // returning a path:
          // function(lngs, namespaces) { return customPath; }
          // the returned path will interpolate lng, ns if provided like giving a static path
          loadPath: '/locales/{{lng}}/{{ns}}.json',
        },

        load: 'currentOnly',
        debug: false,

        interpolation: {
          escapeValue: false, // not needed for react as it escapes by default
        },

        // special options for react-i18next
        // learn more: https://react.i18next.com/components/i18next-instance
        react: {
          wait: true,
        },
      },
      callback
    );

export default i18nInit();

在这里是否可以添加一个功能,从数据库中获取语言值,如果没有设置,则回退到浏览器的区域设置?


我也很想知道本地化翻译是否可以在数据库中获取。手动维护本地化文件夹中的翻译很混乱。 - Luk Aron
2个回答

3
i18next-browser-languageDetector 可以检测用户的浏览器语言,可能与存储在数据库中的值不同。
如果未设置用户语言,您可以向服务器发出 API 调用,然后使用 i18next-browser-languageDetector 作为备用方案。
因此,代码应该如下所示:
export const i18nInit = async (callback = () => { }) => {
  const {lang} = await axios.get('/user-lang');

  const i18nConfig = i18n
    .use(Backend)
    .use(reactI18nextModule);

  if(!lang) {
    i18nConfig.use(LanguageDetector);
  }

  i18nConfig.init({
    lng: lang || undefined // if it has value, it will use this lang, if not, it is undefined as a default value of `lng`
    ...
  });
}

如果你想“高端大气上档次”,你可以编写一个自定义的异步语言检测器,类似于这样:
module.exports = exports = function(fallback){
  return {
    type: 'languageDetector',
    async: true,
    init: () => {},
    detect: async function(callback){
      try {
        await axios.get('user-lang')
          .then(language => {
            if(language){
              return callback(language)
            }

            return callback();
          })
      } catch(error){
        callback();
      }

    },
    cacheUserLanguage: function(language){
      // ... cache users lang
    }
  }
};

基于 i18next-react-native-async-storage

-1

我目前正在尝试设置语言检测器选项为:

const options = {
  order: ['localStorage', 'navigator'],

  lookupLocalStorage: 'i18nextLng',
}

所以我可以先进行axios调用,然后将值设置在localStorage中。如果在localStorage中没有设置该值,则应查找navigator。如果有更好的答案,我会将您的标记为已接受的答案,并在其可行时更新此答案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接