Skip to content
GitHub

Translations

Drupal.t() and Drupal.formatPlural() in theme JS, custom elements included.

Use Drupal's own JS translation API in any theme source: entrypoints, custom elements, Vue components. Strings show up in Configuration → Regional and language → User interface translation like the ones from core.

The same custom element, once in English and once on the German site (/de/…):

Live preview · English Open in new tab ↗
Live preview · Deutsch Open in new tab ↗

The German strings come from a .po file of the docs theme. Translate in the UI or import a file:

drush locale:import de themes/custom/uebertool_docs/translations/de.po
translations/de.po
# German strings of the translations demo, imported with
#   drush locale:import de themes/custom/uebertool_docs/translations/de.po
msgid ""
msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

msgid "Your cart"
msgstr "Dein Warenkorb"

msgid "Welcome back, @name!"
msgstr "Willkommen zurück, @name!"

msgctxt "Sort"
msgid "Order"
msgstr "Reihenfolge"

msgid "1 item"
msgid_plural "@count items"
msgstr[0] "1 Artikel"
msgstr[1] "@count Artikel"
translated-cart.idle.ce.ts
/**
 * Translatable strings in a lazily loaded custom element.
 *
 * @element demo-translated-cart
 *
 * @attr {number} count - Number of items in the cart.
 */
export class TranslatedCart extends HTMLElement {
  connectedCallback() {
    const count = Number(this.getAttribute('count') ?? 0)

    // Plain string.
    const title = Drupal.t('Your cart')
    // Placeholders: @ escapes, % escapes and emphasizes.
    const greeting = Drupal.t('Welcome back, @name!', { '@name': 'Drupal' })
    // Context, for words with several meanings.
    const order = Drupal.t('Order', {}, { context: 'Sort' })
    // Singular and plural, @count is filled in.
    const items = Drupal.formatPlural(count, '1 item', '@count items')

    this.innerHTML = `
      <h3>${title}</h3>
      <p>${greeting}</p>
      <p>${items} · ${order}</p>
    `
  }
}
templates/demos/translations.html.twig
<demo-translated-cart count="3"></demo-translated-cart>

What you can write

Locale finds strings with a regular expression, not by running your code. Only literal strings in '…' or "…" are picked up.

// Plain string.
Drupal.t('Your cart')

// Placeholders: @name is escaped, %name is escaped and emphasized,
// !name is inserted as is.
Drupal.t('Welcome back, @name!', { '@name': user.name })

// Context, for words with several meanings.
Drupal.t('Order', {}, { context: 'Sort' })

// Singular and plural. @count is set for you.
Drupal.formatPlural(count, '1 item', '@count items')
Drupal.formatPlural(count, '1 item in @cart', '@count items in @cart', { '@cart': name }, { context: 'Shop' })

These are not found, the string stays English:

const label = 'Your cart'
Drupal.t(label) // variable instead of a literal

Drupal.t(`Your cart`) // backticks, use '…' or "…"
Drupal.t(`Hello ${name}`) // expression in the string, use a placeholder

const { t } = Drupal
t('Your cart') // has to be called as Drupal.t()

How strings reach locale

Locale only scans the JS files of a library that Drupal loads. That misses chunks loaded with import(), i.e. every custom element, and everything in dev, where the JS comes from Vite. So the plugin lists each source file under js/, templates/ and components/ that calls Drupal.t() or Drupal.formatPlural() in dist/translations.json:

dist/translations.json
{
  "root": "..",
  "files": [
    "templates/demos/translations/translated-cart.idle.ce.ts"
  ]
}

With uebertool_companion enabled, Drupal hands these source files to locale. A content hash in the path makes sure a changed file is parsed again.

  • New strings show up after drush cr.
  • Deploy the source files along with dist/.
  • Locale reads the sources, not the bundle. The minifier may rewrite the strings in dist/, at runtime only the Drupal.t() call matters.