简体   繁体   English

创建类似JavaScript I18n国际化的Lua

[英]Create a Lua like JavaScript I18n internationalization

In our Freifunk project gluon , we use i18n GNU gettext internationalisation in our Lua code (for example for the package gluon-config-mode-hostname ) we create separate files in a subfolder i18n . Freifunk项目gluon中 ,我们在Lua代码中使用了i18n GNU gettext国际化(例如,对于gluon-config-mode-hostname ),我们在子文件夹i18n创建了单独的文件。 I want to use this .po files to add them in our status-page javascript code: https://github.com/rubo77/gluon/tree/status-i18n/package/gluon-status-page/i18n 我想使用此.po文件将它们添加到我们的状态页javascript代码中: https : //github.com/rubo77/gluon/tree/status-i18n/package/gluon-status-page/i18n

Those contain the translations created by the msginit program. 这些包含由msginit程序创建的翻译。

How can I use the same i18n files for the javascript based status-page (without jQuery) to translate those strings? 如何在基于javascript的状态页(无jQuery)中使用相同的i18n文件来转换这些字符串?

Here's a dirty but verbose way of accomplishing it. 这是一种肮脏但冗长的方法。 Is this what you're looking for? 这是您要找的东西吗?

 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> 

NB : Above example likely only works in Chrome. 注意 :上面的示例可能仅适用于Chrome。 Here's a JSBin that should work in FF. 这是应该在FF中工作的JSBin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM