创建类 Lua 的 JavaScript 国际化 (I18n)

在我们的 Freifunk 项目 gluon 中,我们在 Lua 代码中使用 GNU gettext 国际化 (例如对于 gluon-config-mode-hostname 包),我们在一个名为 i18n 的子文件夹中创建单独的文件。我想使用这些 .po 文件将它们添加到我们的状态页面 javascript 代码中: https://github.com/rubo77/gluon/tree/status-i18n/package/gluon-status-page/i18n

这些文件包含通过 msginit 程序创建的翻译。

我该如何在基于 javascript 的状态页面(没有 jQuery)中使用相同的 i18n 文件来翻译这些字符串?

点赞
用户1132995
用户1132995

以下是一种冗长但可行的方式。这是你想要的吗?

let url = "https://raw.githubusercontent.com/rubo77/gluon/status-i18n/package/gluon-status-page/i18n/de.po"

fetch(url)
  .then((res) => {
    return res.body.getReader();
  })
  .then((reader) => {
    return reader.read();
  })
  .then((stream) => {
    let decoder = new TextDecoder();
    let body = decoder.decode(stream.value || new Uint8Array);
    return body
  })
  .then((body) => {
    let text = body.replace(/\\n/g, '');
    let lines = text.split('\n');

    console.log(text)

    let arr = []
    let obj = {}

    for (let i = 0; i < lines.length; i++) {

      // key:value pairs
      if (lines[i].indexOf(':') !== -1) {
        let line = lines[i].replace(/"/g, '');
        let pair = line.split(':');
        if (pair.length) {
          obj[pair[0]] = pair[1].trim();
        }
      }


      // msgid
      if (lines[i].indexOf('msgid') !== -1) {
        let msgobj = {};
        let msgid = lines[i].split(' "')[1].replace(/\"/g, '');
        msgobj.msgid = msgid;

        // msgstr
        if (lines[i+1].indexOf('msgstr') !== -1) {
          let msgstr = lines[i+1].split(' "')[1].replace(/\"/g, '');
          msgobj.msgstr = msgstr;
        }

        arr.push(msgobj);

      }

    }

    arr.push(obj)


  document.getElementById('output-source')
    .innerHTML = body

  document.getElementById('output-js')
    .innerHTML = JSON.stringify(arr, null, 2);
});
.output {
  background-color: #fafafa;
  border: 1px solid #e1e1e1;
}
<pre id="output-source" class="output"></pre>
<pre id="output-js" class="output"></pre>

注意: 上面的例子可能只在 Chrome 中有效。这是一个在 FF 中有效的 JSBin

2017-01-04 08:18:07