Skip to content

Translating a xite

This page explains how to offer a xite in more than one language. It is for xite authors, and it also corrects an assumption carried over from the archived Python implementation: the current node does not translate your files for you. Translation happens in the page, using dictionaries you ship with the xite.

What the node provides

The node has one interface language per installation. The visitor sets it in the Dashboard's Settings, or as Interface language on the Config page. The default is en.

The node gives your page that choice in two ways:

Mechanism Detail
serverInfo The result has a language field, for example "de".
HTML placeholder When serving an .html file, the node replaces the text lang={lang} with lang=<code>, for example <script src="js/app.js?lang=de">.

That is all. In particular:

  • The translate list in content.json, which made the Python node rewrite the listed files while serving them, is not read by the current node. Files are served as they are, apart from the HTML placeholders.
  • There is no special handling of a languages/ directory. It is a naming convention shared by the official xites, and its files are ordinary signed files.

The node translates its own interface, such as the xite sidebar, separately. That does not involve your xite.

The convention

The official xites all follow the same pattern, and using it keeps your xite familiar to contributors:

  1. English strings in the source are the keys.
  2. One dictionary per language lives at languages/<code>.json, mapping each English string to its translation.
  3. A small helper loads the dictionary for the visitor's language at startup and exposes a lookup function named _.
  4. A missing dictionary or a missing key falls back to English.
languages/
├── de.json
├── fr.json
├── pt-br.json
└── zh.json

English is the fallback built into the source, so an en.json is not needed.

Worked example: Epix Talk

Epix Talk ships twenty dictionaries. Here is its mechanism, reduced to the essentials.

The dictionary

languages/de.json
{
  "Follow in Newsfeed": "Im Newsfeed folgen",
  "Following": "Du folgst",
  "Comments in this topic": "Kommentare in diesem Thema",
  "New topics": "Neue Themen",
  "Loading...": "Laden...",
  "Topic title": "Thementitel",
  "Create topic": "Thema erstellen",
  "Newest topics": "Neueste Themen"
}

The helper

The dictionary is read with fileGet, not with fetch, so loading works in every access mode, including gateways where the page has an opaque origin. required: false makes a missing dictionary return null immediately instead of waiting for a download.

js/utils/Translate.js
(function() {
var _translations = {};

window.loadLanguage = function(lang, cb) {
  if (!lang || lang === "en") {
    if (cb) cb();
    return;
  }
  Page.cmd("fileGet", {"inner_path": "languages/" + lang + ".json", "required": false}, function(data) {
    if (data) {
      try {
        _translations = JSON.parse(data);
      } catch (e) {
        _translations = {};
      }
    } else {
      _translations = {};
    }
    if (cb) cb();
  });
};

window._ = function(s) {
  if (_translations && _translations[s]) {
    return _translations[s];
  }
  return s;
};
})();

Loading at startup

Talk asks for serverInfo first, loads the language, and only then renders:

js/EpixTalk.js (excerpt)
onOpenWebsocket() {
  this.cmd("serverInfo", {}, (ret) => {
    this.server_info = ret;
    var afterLang = () => {
      translateDOM();
      this.cmd("siteInfo", {}, (site) => {
        // ... continue booting
      });
    };
    if (ret.language) {
      loadLanguage(ret.language, afterLang);
    } else {
      afterLang();
    }
  });
}

Loading the dictionary before the first render avoids a flash of English text.

Using it

In JavaScript, wrap every user-visible string:

$(".topics-title").text(_("Newest topics"));
menu.addItem(_("Create a topic"), onCreate);
input.setAttribute("placeholder", _("Topic title"));

Static text in index.html cannot call a function, so Talk translates it after load with a table of selectors. A simplified version:

js/utils/Translate.js (continued, simplified)
window.translateDOM = function() {
  var selectors = {
    ".topics-title": "Newest topics",
    ".topics-loading": "Loading...",
    ".topic-new .button-submit": "Create topic",
    ".topic-new #topic_title": {"attr": "placeholder", "text": "Topic title"}
  };
  for (var sel in selectors) {
    var val = selectors[sel];
    if (typeof val === "object") {
      $(sel).attr(val.attr, _(val.text));
    } else {
      $(sel).each(function() {
        if ($(this).children().length === 0) $(this).text(_(val));
      });
    }
  }
};

A lighter alternative for your own xites is a data attribute, which keeps the string next to the markup:

<h2 data-i18n="Newest topics">Newest topics</h2>
document.querySelectorAll("[data-i18n]").forEach(function(el) {
  el.textContent = _(el.getAttribute("data-i18n"));
});

Add translation to your xite

  1. Add the helper above as js/utils/Translate.js and include it before your application script. It expects your EpixFrame instance to be available as Page.
  2. Wrap strings with _("..."), using clear English sentences as keys.
  3. In onOpenWebsocket, request serverInfo, call loadLanguage(info.language, start) and render in start.
  4. Create languages/<code>.json for each language you support.
  5. Sign and publish. The dictionaries are listed in content.json like any other file.

Language codes

The code is whatever the visitor's node is set to. The Dashboard's language picker offers these codes, which are the file names the official xites use:

ar  da  de  en  es  fa  fr  hu  it  jp  kr  nl  pl  pt  pt-br  ru  sk  sl  tr  uk  zh  zh-tw

Note jp and kr rather than ja and ko. Match these names so your dictionaries are found. serverInfo reports the configured value as it is. For the lang={lang} placeholder the node keeps only ASCII letters, digits and hyphens (at most 16 characters) and uses en when nothing is left.

Letting visitors choose inside your xite

The node language is a sensible default, but changing it requires the ADMIN permission (it is a node setting, changed with configSet), which an ordinary xite does not have and should not ask for. If you want a language menu in your own xite, keep the choice per visitor:

// Save the visitor's choice for this xite and apply it.
function chooseLanguage(lang) {
  Page.cmd("wrapperSetLocalStorage", { language: lang });
  loadLanguage(lang, render);
}

// At startup: the saved choice wins over the node language.
Page.cmd("wrapperGetLocalStorage", [], function(data) {
  var saved = data && data.language;
  Page.cmd("serverInfo", {}, function(info) {
    loadLanguage(saved || info.language, render);
  });
});

If you already keep other values in wrapper local storage, merge the language key into that object rather than replacing it.

Things to get right

  • Dictionaries are signed files. After editing languages/*.json in your working copy, sign the xite. If the xite has a dbschema.json, this matters beyond translation: every declared .json file is a verified database input, and a dictionary that no longer matches its signed hash, or is not valid JSON, can leave the xite without a database until you sign again. See Only signed inputs are loaded.
  • Translate text, never markup from users. Set translated strings with textContent or .text(). If a translation needs markup, keep the markup in your code and translate the pieces.
  • Keys are exact. "Loading..." and "Loading…" are different keys. Changing an English string in the source orphans its translations, so search the dictionaries when you edit a key.
  • Handle interpolation yourself. The helper does plain lookup. For sentences with values, translate a template and substitute: _("{count} comments").replace("{count}", n).
  • Dates and numbers can use the browser: new Date(ts * 1000).toLocaleDateString(lang) and Number(n).toLocaleString(lang). Map jp to ja and kr to ko first, since those are not valid browser locale codes.
  • Right-to-left languages. For ar and fa, set document.documentElement.dir = "rtl" when the language loads and test your layout.
  • Cache busting. If you load a script per language, use the placeholder so each language gets its own URL: <script src="js/app.js?lang={lang}"></script>.

Migrating a xite from the Python node

If your xite relied on server-side translation:

  1. Keep your languages/*.json files. The format, English string to translated string, is unchanged.
  2. Add a client-side helper as shown above and pass every visible string through _() at render time. The old node replaced matching quoted strings inside the files listed in translate while serving them; the current node serves those files unchanged, so a string that is not looked up at run time stays in English. Load the helper before any script that calls _().
  3. Leave or remove the translate list in content.json. It has no effect either way.

More on differences between the implementations is in Interoperability with the Python implementation.