Translating programmatically

There are occurrences of texts to translate that can appear outside the DOM subtree handled by Tolgee or as visible properties of DOM objects such as value of <input> element or document title. Tolgee won't translate them automatically. (Hopefully in future versions)

There is a certain way how to deal with these.

In our Hello world example there is a title element which is not translated. We can translate it by adding this code snipped to our javascript part of the document:

tg.onLangLoaded.subscribe(() => {
document.title = tg.instant("hello_world", undefined, true);

Getter tg.onLangLoaded returns an instance of EventEmitter. The callback of subscribe method is called every time language changes and Tolgee loads its translations. So after that, we can call tg.instant, what returns the translations from already loaded translations. First parameter of this method is the translation key in our case "hello_world". Second parameter is object of translation parameters (see parameter interpolation). The last parameter noWrap tells Tolgee not to wrap it with inputPrefix and inputSuffix values. In general, it means that Tolgee will return the translated value instead of wrapped value like {{hello_world}}. This is useful for occurrences where it is impossible to click on the translated element or where Tolgee could not find the value by inspecting DOM (see understanding Tolgee).


If you can see wrapped text on rendered page such as {{something}} or
%-%tolgee:something%-% you should probably try to translate it programmatically with third parameter set to true like:

tg.instant("something", undefined, true)


tg.translate("something", undefined, true).then(translation => {})

Full HTML example page is here:

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>hello world</title>
<div id="loading" style="
position: fixed;
left: 0;
width: 100%;
height: 100%;
background-color: white;
display: flex;
align-items: center;
justify-content: center;
<script src=""></script>
<script src=""></script>
const tg = new window["@tolgee/core"].Tolgee({
apiUrl: "",
apiKey: "you_secret_api_key",
inputPrefix: "{{",
inputSuffix: "}}",
watch: true,
ui: window["@tolgee/ui"].UI,
}); => {
document.getElementById("loading").style.display = "none";
tg.onLangLoaded.subscribe(() => {
document.title = tg.instant("hello_world", undefined, true);

translate method#

Tolgee.translate method returns your translation asynchronously and returns Promise. In general it is more secure to use it. Instant method can return untranslated key when translations are not loaded yet.

tg.translate("hello_world", undefined).then(t => {document.body.innerText = t});

instant method#

On the other hand tg.instant method returns translation immediately. However, if translations are not loaded yet, it returns untranslated localization key.

const translation = tg.instant("hello_world");