Skip to content

Translations

loadTranslations(url, options) loads the plugin's strings in the viewer's language from the plugin's translations endpoint, and returns a handle that reads, formats, cases, and applies them. The handle becomes the page's current translations, which every component reads its default text from. titleCase and sentenceCase convert English text. How a plugin declares Jellyfin strings and adds its own is on Translations.

Decision

When Use
Text on a config page or a standalone page in the viewer's language loadTranslations, then t.tr and t.format
Static markup with a key data-str, data-str-title, data-str-label, or data-str-placeholder, then t.apply(root)
Strings that came another way, such as in a page's first response createTranslations(strings, language)
A count in a sentence t.format('QuotaLeft', used, total), with the plural forms as separate keys
A string in title case or sentence case t.title(key) or t.sentence(key)
Any English text in title case or sentence case titleCase(text, options) or sentenceCase(text, options)
Components in the viewer's language loadTranslations before building them
Text the server writes, such as an activity entry StolonTranslations in C#

Usage

import { loadTranslations } from './configurationpage?name=myplugin_stolon.js';

loadTranslations('MyPlugin/Translations').then(function (t) {
    t.apply(view);
    view.querySelector('#quota').textContent = t.format('QuotaLeft', 3, 5);
});
<h2 data-str="MyRequests">My Requests</h2>
<input data-str-placeholder="Search" placeholder="Search">

Load the translations before building components, so their default text is translated.

loadTranslations('MyPlugin/Translations').then(function (t) {
    t.apply(view);
    createPaginatedTable(view, shared, { containerId: 'rows', endpoint: 'Rows', columns: columns });
});

The endpoint answers with StolonTranslations.Serve. A relative address goes through ApiClient.getUrl, so the page works on a server hosted under a base URL. A standalone page with no ApiClient passes an address that starts with /.

States and Modifiers

  • The language is options.language, else the viewer's display setting in the web client, else the browser's language. options.userId names whose display setting to read on a page with no ApiClient.
  • tr(key, fallback) gives the string, else fallback, else the key.
  • has(key) is true only for a key the plugin has a string for.
  • currentLanguage() reads the viewer's language on its own, and formatText(text, ...args) fills placeholders in any text.
  • currentTranslations() gives the page's current translations, the handle loadTranslations gave last, or null.
  • t.title(key) and t.sentence(key) convert in the handle's language, so only English changes, and keep the words of t.casing, Stolon's defaults and the plugin's casing list.
  • titleCase and sentenceCase keep Stolon's defaults, the casing list of the page's current translations, and options.exceptions. They convert English, the default, and return text in any other options.language as it is. The rules are on Casing.

Gotchas

  • A load never rejects. A failed load gives a handle with no strings, so the page shows its fallbacks, and the next call asks again.
  • Each address and language is loaded once per page load.
  • apply sets text only, never HTML. Markup whose key has no string keeps its own text.
  • A component reads its default text when it is built. One built before the translations load stays in US English until it is built again.
  • A failed load keeps the translations an earlier load made current.
  • The endpoint answers with { language, strings, casing }. A plain object of strings also loads, with no casing list.

Reference

formatText

function formatText(text: string, ...args: unknown[]): string

Fills the {0}, {1} placeholders of a text with the values after it. A placeholder with no value is kept.

currentLanguage

function currentLanguage(userId?: string): string

Reads the viewer's language as the web client picks it: their display setting, else the browser's language.

titleCase

function titleCase(text: string, options?: CaseOptions): string

Writes English text in title case, such as "Allow Media Playback", with the same rules as TextCase.ToTitleCase in C#. Short words such as of and the stay lower case unless first, last, or after a colon. Any other language returns the text as it is.

Option Type What it does
exceptions string[]
language string

sentenceCase

function sentenceCase(text: string, options?: CaseOptions): string

Writes English text in sentence case, such as "Allow media playback", with the same rules as TextCase.ToSentenceCase in C#. Words with a capital inside them, such as TV or iPhone, stay as written. Any other language returns the text as it is.

Option Type What it does
exceptions string[]
language string

currentTranslations

function currentTranslations(): TranslationsHandle | null

The page's current translations: the handle loadTranslations gave last, which every component reads its default text from. null until a load finishes.

Handle member Type
language string
strings Record<string, string>
casing string[]
tr (key: string, fallback?: string): string
format (key: string, ...args: unknown[]): string
title (key: string): string
sentence (key: string): string
has (key: string): boolean
apply (root?: ParentNode): void

createTranslations

function createTranslations(strings: Record<string, string>, language?: string, casing?: string[]): TranslationsHandle

Builds a translations handle over strings already loaded.

Handle member Type
language string
strings Record<string, string>
casing string[]
tr (key: string, fallback?: string): string
format (key: string, ...args: unknown[]): string
title (key: string): string
sentence (key: string): string
has (key: string): boolean
apply (root?: ParentNode): void

applyTranslations

function applyTranslations(translations: TranslationsHandle, root?: ParentNode): void

Translates marked markup under a root. data-str sets the text, and data-str-title, data-str-label, and data-str-placeholder set the title, aria-label, and placeholder. A key with no string keeps the markup's own text.

Option Type What it does
language (required) string
strings (required) Record<string, string>
casing (required) string[]
tr (required) (key: string, fallback?: string): string
format (required) (key: string, ...args: unknown[]): string
title (required) (key: string): string
sentence (required) (key: string): string
has (required) (key: string): boolean
apply (required) (root?: ParentNode): void

loadTranslations

function loadTranslations(url: string, options?: TranslationsOptions): Promise<TranslationsHandle>

Loads the plugin's strings in the viewer's language from its translations endpoint, once per address and language. It never rejects. A failed load gives a handle with no strings, so every tr falls back. The handle becomes the page's current translations, which components read their default text from, so load them before building components. The endpoint answers with { language, strings, casing }, or with the strings alone.

Option Type What it does
language string
userId string

Example

Example Code

<!-- title: Translations -->
<div style="display: flex; flex-direction: column; gap: 10px;">
    <div style="display: flex; flex-wrap: wrap; gap: 10px; align-items: center;">
        <button type="button" class="raised stolon-button stolon-secondary stolon-small" data-language="en-us"><span>English</span></button>
        <button type="button" class="raised stolon-button stolon-secondary stolon-small" data-language="de"><span>Deutsch</span></button>
        <button type="button" class="raised stolon-button stolon-secondary stolon-small" data-language="fr"><span>Français</span></button>
    </div>
    <h3 data-str="MyRequests">My Requests</h3>
    <input is="emby-input" type="text" data-str-placeholder="Search" placeholder="Search">
    <span id="quota" class="stolon-mono"></span>
</div>
<script type="module">
const base = await window.__baseReady;
const strings = {
    'en-us': { MyRequests: 'My Requests', Search: 'Search', QuotaLeft: '{0} of {1} left' },
    'de': { MyRequests: 'Meine Anfragen', Search: 'Suche', QuotaLeft: '{0} von {1} übrig' },
    'fr': { MyRequests: 'Mes demandes', Search: 'Rechercher', QuotaLeft: '{0} sur {1} restants' }
};
// The preview answers in place of a plugin's StolonTranslations.Serve endpoint.
const realFetch = window.fetch;
window.fetch = (url, init) => {
    const match = /\/Preview\/Translations\?language=([\w-]+)/.exec(String(url));
    if (!match) return realFetch(url, init);
    return Promise.resolve(new Response(JSON.stringify(strings[match[1]] || strings['en-us']), { headers: { 'Content-Type': 'application/json' } }));
};
const show = async (language) => {
    const t = await base.loadTranslations('/Preview/Translations', { language });
    t.apply(document.body);
    document.getElementById('quota').textContent = t.format('QuotaLeft', 3, 5);
};
document.querySelectorAll('[data-language]').forEach((b) => b.addEventListener('click', () => show(b.dataset.language)));
show('en-us');
</script>