DocsVue

@generic-translation/vue reference

createGenericTranslation options, composables, components, the template serialization rules and what is rejected inside T.

On this page

Vue 3 bindings for Generic Translation: <T> for template content, t() / $t for ICU strings, d() / $d for dictionary entries, and formatting components. Source: generic-translation/generic-translation-vue. To get started, see the quickstart.

@generic-translation/vue is not published to npm yet. Clone generic-translation/generic-translation with --recurse-submodules, build packages/core and packages/vue, and link them. Peer dependency: vue ^3.4.

createGenericTranslation(options)

A Vue plugin for app.use(). It creates an isolated state; create one per app, and one per request when server-rendering. Nothing is kept in module-level state, so concurrent requests never share a locale or translations.

Option Type Description
locale string Locale to render first. Give it, with translations, when server-rendering so hydration matches. Without it the app starts in defaultLocale and, after mount, switches to the saved (generic-translation-locale cookie, then localStorage) or browser language.
defaultLocale string Locale your source is written in. Default "en".
locales string[] Target locales. The default locale is added first automatically.
translations Record<hash, string> Initial translation map for locale.
loadTranslations (locale) => Promise<map> Loads a locale’s map before switching to it.
projectId, baseUrl string Without loadTranslations, maps come from the Generic Translation CDN.
devApiKey string Development only. Missing strings are batched (50 ms debounce, at most 50 per request) and translated on demand. Ignored, with a console error, when NODE_ENV is production. Never ship an API key to browsers.
dictionary nested JSON Source dictionary for useDictionary() / $d.
onLocaleChange (locale) => void Called after a switch is applied.
detectLocale boolean Default true; only applies when locale is not given.
updateHtmlAttributes boolean Keep <html lang dir> in sync. Default true, browser only.
registerComponents boolean Register the components globally. Default true.

The plugin also exposes the state: locale (a readonly ref), defaultLocale, locales, translations, isLoading, setLocale(locale), ready() (resolves when the current locale’s map is loaded; await it on the server), loadLocale(locale), getTranslations(locale?), t and d. It installs $t, $d and $genericTranslation on every component, and starts locale detection and <html> updates only after app.mount(), so hydration always sees the server’s locale first.

GenericTranslationProvider

A component alternative that takes the same options as props (except registerComponents) and provides an isolated state to its subtree. It emits localeChange. The locale prop is followed when it changes; other props are read once. $t and $d resolve the nearest provider above the component whose template calls them, but they exist only when the plugin is installed, so with <GenericTranslationProvider> alone use useGenericTranslation() and useDictionary().

Composables

Composable Returns
useGenericTranslation() t(message, values?). message is an ICU string literal; values.$context disambiguates (it is part of the hash) and $id is metadata. Falls back to the formatted source. Reactive in templates, render functions and computed.
useDictionary() d(id, values?), where id is a dot path. Leaves are "message" or ["message", { "context": "…" }]. Unknown ids return the id.
useLocale() ComputedRef<string>, the current locale.
useSetLocale() (locale) => Promise<void>. Persists the choice (cookie generic-translation-locale plus localStorage), loads the map, then switches. Unknown locales are matched with determineLocale ("de-AT" to "de") or ignored.
useLocales() ComputedRef<string[]>, default first.
useLocaleProperties(locale?) ComputedRef<LocaleProperties> with names in the current locale.
useLocaleDirection(locale?) ComputedRef<"ltr" | "rtl">.
useGenericTranslationState() The raw state.

Outside any plugin or provider the composables and components work against a source-only default (English, no translations).

Components

  • <T context? id?> translates its content as one message. With no translation, untranslatable content, or outside a plugin it renders the source.
  • <Var name? :value?> is dynamic content ({name}). The slot content or value is inserted untouched.
  • <Num name? :value? :options? :locales?> uses Intl.NumberFormat ({name, number}).
  • <Currency name? currency="EUR" :value? :options?> gives {name, number, ::currency/EUR}. currency defaults to USD.
  • <DateTime name? :value? :options?> gives a medium date by default ({name, date, medium}).
  • <RelativeTime :date :now? /> or <RelativeTime :value="-3" unit="day" />. Standalone only; inside <T> it is an ordinary tag.
  • <Plural :n name? zero? one? two? few? many? other?> with #zero #one #two #few #many #other slots (the default slot is other). Inside <T> it is an ICU plural using the target locale’s rules; standalone it picks a branch with the default locale’s rules.
  • <Branch :branch name? key="…"> with #key slots (the default slot is the fallback). Inside <T> it is an ICU select.
  • <LocaleSelector :names? show-emoji> is a <select> of the locales in their own language. It emits change(locale); other attributes pass through.

Num, Currency and DateTime read their value from value or from the slot text. serializeVNodes(vnodes, context?) serializes <T> content without rendering, which is handy in tests. createGenericTranslationState(options) and GENERIC_TRANSLATION_KEY let you provide a state yourself.

Serialization

This describes how the content of a <T> element becomes a Generic Translation message. The runtime implements it on the VNodes Vue’s compiler produces, and the CLI implements it on the template AST from @vue/compiler-dom. Both build the same message tree and call serializeJsx() from @generic-translation/core, so messages and hashes are byte-identical. The README’s fixtures and a reference static extractor are part of the package’s test suite.

Pipeline

  1. Parse the template the way Vue does, with the default whitespace: "condense", to get the children of <T>.
  2. Map the children to a node list, then trim the roots.
  3. Serialize with serializeJsx.
  4. The hash is hashSourceSync({ source: message, context }). context is the context attribute of <T>; it is omitted when absent or empty. id is never hashed.
  5. At runtime, a missing, unparsable or incompatible translation (or a locale that needs none) renders the source message.

Recognizing Generic Translation components

A tag is a Generic Translation component X (T, Var, Num, Currency, DateTime, Plural, Branch) when either the SFC imports X from @generic-translation/vue and the tag is its local name (so import { Var as V } makes <V> a Var), or the tag is exactly the PascalCase name. Kebab-case spellings (<date-time>) and namespaced tags (<L.Var>) are not recognized by the CLI, so do not use them inside <T>. Every other tag, including RelativeTime, LocaleSelector, a nested T and your own components, is an ordinary element.

Text

Text is exactly what Vue’s template parser produces with whitespace: "condense":

  1. HTML character references are decoded first (&amp;, &#32;, &nbsp; to U+00A0), so an encoded space is ordinary whitespace afterwards.
  2. Whitespace means only space, tab, \n, \r and form feed. U+00A0 and other Unicode spaces are ordinary characters.
  3. A whitespace-only text node is removed if it is the first or last child, or if it sits between two elements and contains a line break. Otherwise it becomes a single space.
  4. Any other text node has each run of whitespace replaced by a single space.

Mapping

Template child Becomes
Text text
<Var name? :value?> {name}
<Num> {name, number}
<Currency currency?> {name, number, ::currency/XXX}; currency defaults to USD and must be a literal
<DateTime> {name, date, medium}
<Plural :n …> an ICU plural (below)
<Branch :branch …> an ICU select (below)
any other element or component (<b>, <a href>, <br/>, <RouterLink>, <RelativeTime>, a nested <T>) a numbered tag <N>…</N>, or <N/> when it has no children after the text rules. Attributes and directives do not affect the message.
{{ expression }} error
<!-- comment --> error

The children of ordinary elements are not trimmed: <a href="/x">⏎ Docs⏎</a> is <0> Docs </0>, exactly what Vue renders. A literal string means a static attribute, or a v-bind of a single string literal such as :name="'user'".

Names are used only when they are a non-empty literal string. Otherwise they are generated: v0, v1, … for variables, n for plurals and branch for selects. The children or value of Var, Num, Currency and DateTime are the runtime value and are never part of the message.

Plural branches. For each of zero one two few many, a <template #k> slot wins over a literal attribute k; otherwise the branch is absent. other is the #other slot, then the literal other attribute, then the default slot. :n never appears in the message.

Branch keys. Literal attributes in source order come first (except branch, name, other, key, ref, class, style and listeners), then named slots in source order. Because branches is a JavaScript object, integer-like keys (#1, #2) are emitted first in ascending order. The fallback is the default slot, otherwise #other, otherwise the other attribute. Keys must be valid ICU select keys (no whitespace and none of {},'<>#).

Default slot. An explicit <template #default>, otherwise the children that are not <template v-slot>, as long as at least one is not whitespace-only text.

Trimming

The content of <T> and of each Plural or Branch slot is a message root. Leading whitespace of the first text node and trailing whitespace of the last are removed, and adjacent text nodes are merged. So a <T> whose body is Hello <b>world</b>! indented on its own lines is Hello <0>world</0>!. A space you need at the edge of <T> belongs outside it.

Order

Tag numbers (<0>, <1>, …) and auto names are assigned depth-first, parent before children, in emission order. Plural branches are visited zero, one, two, few, many, other regardless of template order; Branch keys follow the key order above, then the fallback.

What is rejected inside <T>

The CLI reports these with file:line:col and skips that <T>. At runtime in development, <T> logs a console error and renders its content untranslated.

Construct Why
{{ expr }} outside Var/Num/Currency/DateTime content the value would become part of the source text
HTML comments Vue keeps them in development and drops them in production, with different whitespace
v-if, v-else-if, v-else, v-for, v-once, v-memo, :key, key on anything in the message the structure would depend on data
<slot> outlets, plain <template> without v-slot, <Teleport>, <KeepAlive>, <Suspense>, <component :is> naming a Generic Translation component not representable as a static message
named slots on anything other than Plural / Branch, dynamic slot names (#[name]), v-if / v-for on slot templates the runtime only renders an element’s default slot
<pre>, <textarea>, v-pre different whitespace rules
v-bind="object" on Plural / Branch; non-literal name, currency or branch attributes; a non-literal context on <T> the CLI cannot see the value
kebab-case or namespaced Generic Translation tags not recognized
whitespace: "preserve" in your Vue compiler options changes every text node

Two limits of runtime detection: a constant interpolation such as {{ 'x' }} compiles to plain text, so the runtime cannot see it. It hashes the text, finds no translation and renders the source. And two variables with the same name but different runtime values (for example two unnamed <Plural>s, both n) make a <T> untranslatable at runtime, so give each a name. The CLI cannot see values and extracts the message anyway.

Examples

Template Message
<T>Hello <b>world</b>!</T> Hello <0>world</0>!
<T>Hello <Var name="user">{{ user.name }}</Var>!</T> Hello {user}!
<T><Var :value="a" /> and <Var :value="b" /></T> {v0} and {v1}
<T>Read the <a href="/docs">docs</a> or <RouterLink to="/help">ask <em>us</em></RouterLink>.</T> Read the <0>docs</0> or <1>ask <2>us</2></1>.
<T><Plural :n="n" name="files" one="One file" other="Many files" /></T> {files, plural, one {One file} other {Many files}}
<T context="button">Save</T> Save, with context button

Rendering

The chosen message is rendered with core’s renderMessage: tag <N> becomes a clone of the N-th original element (props, listeners and directives kept) with the translated children; number, currency and date arguments are formatted in the current locale; plural and select pick branches with the target locale’s rules. Translators may reorder tags and variables but must keep the same set of variable names and tag numbers, or the source is shown.

SSR and hydration

// server (per request)
const genericTranslation = createGenericTranslation({ locale, locales, loadTranslations: readMapFromDisk });
const app = createSSRApp(App).use(genericTranslation);
await genericTranslation.ready();
const html = await renderToString(app);
const state = JSON.stringify({ locale, translations: genericTranslation.getTranslations() });

// client
const { locale, translations } = window.__GENERIC_TRANSLATION__;
createSSRApp(App).use(createGenericTranslation({ locale, locales, translations, loadTranslations })).mount("#app");

Pass the same locale and translations on both sides and the first client render matches the server HTML. Cookies, localStorage, navigator and <html> are only touched in the browser after mount. <RelativeTime :date> needs an explicit now to render identically.

Fallbacks

  • A missing translation, a same-language locale (en-GB for an en source), or an unparsable or incompatible translation renders the source.
  • Content that cannot be serialized logs a development console error and renders untranslated.
  • Missing values render as a literal {name} placeholder; an empty <Var> renders nothing.
  • Failed loads log a warning and keep the source. Nothing throws during render.

CLI extraction

generic-translation translate handles .vue files: <script> and <script setup> blocks, template t() / $t calls (interpolations, bindings, event handlers), and template <T> following the rules above. Because }} ends a Vue interpolation, ICU plurals such as {count, plural, … {# items}} belong in an attribute binding (v-text="t('…')") or in the script. Shadowing of t by v-for or slot props is not tracked, and templates with lang="pug" (or any non-HTML lang) are skipped. See CLI commands.

Something wrong or unclear on this page? Open an issue.

Type to search the documentation.