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
. 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
Those contain the translations created by the msginit program.
How can I use the same i18n files for the javascript based status-page (without jQuery) to translate those strings?
1 Answers
Answers 1
Here's a dirty but verbose way of accomplishing it. Is this what you're looking for?
let url = "https://raw.githubusercontent.com/freifunk-gluon/gluon/master/package/gluon-config-mode-hostname/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. Here's a JSBin that should work in FF.
0 comments:
Post a Comment