【问题标题】:How to use i18next to load resource from PHP?如何使用 i18next 从 PHP 加载资源?
【发布时间】:2019-03-24 12:59:58
【问题描述】:

我有以下 PHP 脚本来加载 i18next 翻译的资源

<?php
$sql = 'SELECT * FROM translations';
...
header('Content-Type: application/json');
echo json_encode($translations);
?>

但是如何将它与我的 react js 应用程序一起使用?最初,我使用客户端中的 json 加载翻译,就像在 i18next 官方教程中所做的那样。

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

import translations from './translations.json';

const resources = translations;

i18n.use(initReactI18next).init({ resources, lng: 'zh', keySeparator: false, interpolation: { escapeValue: false } });

我想在服务器端使用 PHP 加载。但以下方法不起作用:

import i18n from 'i18next';
import xhr from 'i18next-xhr-backend';
import { initReactI18next } from 'react-i18next';
import axios from 'axios';

function loadCurrent(url, options, callback, data) {
    axios.get(url).then((res) => {
       callback(res.data, { status: res.status });
    });
}

const i18nextOpt = {
 backend: {
     loadPath: 'http://localhost/translation.php',
     parse: function(data) { return JSON.parse(data); },
     ajax: loadCurrent
 },  
 getAsync: false
 };

 i18n.use(xhr).init(i18nextOpt);

我应该在我的 React 脚本中进行哪些更改?谢谢。

【问题讨论】:

  • 你不能只使用 fetch 吗?为什么需要 i18next-xhr-backend 和 axios?
  • 以上是我的第一次尝试。我对它不是很熟悉。看来他们不会接受非json文件。
  • 对不起,我对 i18next 也不是很熟悉。我想像:fetch("XXX.php").then((res)=&gt;(res.json())).then((data)=&gt;{i18next.init({resources: data})},但那可能完全不对。

标签: reactjs i18next react-i18next


【解决方案1】:

诀窍是:

通过导入添加资源,您的结构如下:

{ lng: { ns: { key: value } } }

在 xhr 上,每个 lng 命名空间对都是单独加载的……所以文件必须是

{ key: value }

但在 lng / ns 中请求 -> 因此 loadpath 类似于:

http://localhost/{{lng}}/{{ns}}.php

https://www.i18next.com/how-to/add-or-load-translations

不需要 axios 只需使用 xhr-backend

【讨论】:

  • 所以我必须在我的服务器中重命名我的 PHP 脚本?
猜你喜欢
  • 1970-01-01
  • 2021-08-31
  • 1970-01-01
  • 1970-01-01
  • 2017-07-04
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多