ux-translator
Symfony UX Translator: Symfony translations in JavaScript with trans(), ICU and plural support, type-checked keys in TypeScript. Use for createTranslator, var/translations, ux_translator domains or keys_patterns, setLocale, ux:translator:warm-cache.
Install
npx skills add https://github.com/smnandre/symfony-ux-skills/tree/main/skills/ux-translator
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install smnandre-symfony-ux-skills@llmmart
git clone https://github.com/smnandre/symfony-ux-skills.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole smnandre/symfony-ux-skills collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
UX Translator
Use your Symfony translations in JavaScript with a trans() function that behaves like the PHP translator: domains, locales, fallbacks, pluralization and the ICU Message Format. Translations are dumped to var/translations/ on cache warmup; with TypeScript, keys, parameters, domains and locales are type-checked.
Prefer rendering text in Twig when the server already knows it. Reach for UX Translator when JavaScript builds messages itself: client-side validation, toasts, confirmation dialogs, chart labels.
Installation
composer require symfony/ux-translator
Requires StimulusBundle. Flex creates the translator module:
// assets/translator.js (rename to translator.ts for type-checking)
import { createTranslator } from '@symfony/ux-translator';
import { messages, localeFallbacks, defaultLocale } from '../var/translations/index.js';
const translator = createTranslator({
messages,
localeFallbacks,
defaultLocale,
});
export const { trans } = translator;
| Asset pipeline | Extra step |
|---|---|
| AssetMapper | None: Flex adds @symfony/ux-translator to importmap.php, and the bundle maps the dump directory |
| Webpack Encore | npm install --force, then restart npm run watch |
Translating
import { trans } from './translator';
trans('cart.empty'); // domain "messages", current locale
trans('cart.items', { '%count%': 3 }); // pluralization
trans('cart.greeting', { '%name%': 'Fabien' }); // placeholder
trans('cart.title', {}, 'shop'); // another domain
trans('cart.title', {}, 'messages', 'fr'); // another locale
Parameters follow the PHP translator:
- Classic messages replace keys exactly as written in the message:
%name%needs{ '%name%': 'Fabien' }. Pluralization reads%count%({0} No item|{1} One item|]1,Inf] %count% items). - ICU messages (files named
messages+intl-icu.fr.yaml) take plain names:{ count: 3, name: 'Fabien' }. Keys wrapped in%or{}are accepted too. The domain staysmessages: the ICU version wins when both exist.
A missing key returns the key itself.
Choosing What Is Dumped
Every domain and key is dumped by default, and all of it ends up in the JavaScript bundle. Narrow it:
# config/packages/ux_translator.yaml
ux_translator:
domains: [messages, validators] # or '!admin', or ['!admin', '!security']
keys_patterns: ['app.*', '!app.internal.*']
* matches any characters; a leading ! excludes. Avoid exposing admin or internal wording: anyone loading your JavaScript can read it.
Locale
The locale is the first one found in:
- the
localeoption ofcreateTranslator(); <html data-symfony-ux-translator-locale="{{ app.request.locale }}">(Symfony format,de_AT);<html lang="{{ app.request.locale|replace({'_': '-'}) }}">(W3C format,de-AT);- the
defaultLocaleoption, since Symfony UX 3.7+ (the dump exportsframework.default_locale); en.
Change it at runtime with setLocale(); read it with getLocale():
export const { trans, setLocale, getLocale } = translator;
setLocale('de_AT');
Fallbacks follow localeFallbacks from the dump, as in PHP (de_AT falls back to de).
Missing Translations
const translator = createTranslator({
messages,
localeFallbacks,
defaultLocale,
throwWhenNotFound: true,
});
export const { trans, setThrowWhenNotFound } = translator;
Enable it in development or tests to catch keys missing from the dump.
Dumping
Translations are dumped on cache warmup. Since Symfony UX 3.1+, refresh only the JavaScript translations with:
php bin/console ux:translator:warm-cache
Configuration
# config/packages/ux_translator.yaml (defaults)
ux_translator:
dump_directory: '%kernel.project_dir%/var/translations' # update assets/translator.js if changed
dump_typescript: true
domains: ~ # all domains
keys_patterns: [] # all keys
AssetMapper never reads the TypeScript types, so skip them in production there:
when@prod:
ux_translator:
dump_typescript: false
Keep them with Encore or Reprise and TypeScript: the build type-checks against them.
Gotchas
- Placeholder not replaced: classic messages need the full key (
'%name%'), plainnameonly works for ICU messages. - Plural ignored: pass
%count%as a number for classic messages,countfor ICU. - New key returns the key itself: the dump is stale or the key is filtered out. Run
ux:translator:warm-cacheand checkdomains/keys_patterns. - Empty
var/translations/on CI or in a Docker build stage: runcache:warmupbefore the asset build, and copy the directory into the Node stage. - Wrong locale: set
data-symfony-ux-translator-localeorlangon<html>fromapp.request.locale. - Bundle too large: filter with
domainsandkeys_patterns.
References
- Symfony UX package page (Markdown summary) ·
symfony/ux-translatoron Packagist. - Try the JavaScript translation demo.
- For dumping catalogs, configuring locale and translating in JavaScript, see the Symfony UX Translator documentation.
See Also
- stimulus: import
trans()in a controller for client-side messages. - ux-router: same dump model for routes (
var/routes/,path()in JavaScript).
Files (symfony-ux-skills)
-
SKILL.md 6 KB
--- name: ux-translator description: 'Symfony UX Translator: Symfony translations in JavaScript with trans(), ICU and plural support, type-checked keys in TypeScript. Use for createTranslator, var/translations, ux_translator domains or keys_patterns, setLocale, ux:translator:warm-cache.' license: MIT metadata: author: Simon André url: https://smnandre.dev --- # UX Translator Use your Symfony translations in JavaScript with a `trans()` function that behaves like the PHP translator: domains, locales, fallbacks, pluralization and the ICU Message Format. Translations are dumped to `var/translations/` on cache warmup; with TypeScript, keys, parameters, domains and locales are type-checked. Prefer rendering text in Twig when the server already knows it. Reach for UX Translator when JavaScript builds messages itself: client-side validation, toasts, confirmation dialogs, chart labels. ## Installation ```bash composer require symfony/ux-translator ``` Requires StimulusBundle. Flex creates the translator module: ```javascript // assets/translator.js (rename to translator.ts for type-checking) import { createTranslator } from '@symfony/ux-translator'; import { messages, localeFallbacks, defaultLocale } from '../var/translations/index.js'; const translator = createTranslator({ messages, localeFallbacks, defaultLocale, }); export const { trans } = translator; ``` | Asset pipeline | Extra step | |----------------|------------| | AssetMapper | None: Flex adds `@symfony/ux-translator` to `importmap.php`, and the bundle maps the dump directory | | Webpack Encore | `npm install --force`, then restart `npm run watch` | ## Translating ```javascript import { trans } from './translator'; trans('cart.empty'); // domain "messages", current locale trans('cart.items', { '%count%': 3 }); // pluralization trans('cart.greeting', { '%name%': 'Fabien' }); // placeholder trans('cart.title', {}, 'shop'); // another domain trans('cart.title', {}, 'messages', 'fr'); // another locale ``` Parameters follow the PHP translator: - **Classic messages** replace keys exactly as written in the message: `%name%` needs `{ '%name%': 'Fabien' }`. Pluralization reads `%count%` (`{0} No item|{1} One item|]1,Inf] %count% items`). - **ICU messages** (files named `messages+intl-icu.fr.yaml`) take plain names: `{ count: 3, name: 'Fabien' }`. Keys wrapped in `%` or `{}` are accepted too. The domain stays `messages`: the ICU version wins when both exist. A missing key returns the key itself. ## Choosing What Is Dumped Every domain and key is dumped by default, and all of it ends up in the JavaScript bundle. Narrow it: ```yaml # config/packages/ux_translator.yaml ux_translator: domains: [messages, validators] # or '!admin', or ['!admin', '!security'] keys_patterns: ['app.*', '!app.internal.*'] ``` `*` matches any characters; a leading `!` excludes. Avoid exposing admin or internal wording: anyone loading your JavaScript can read it. ## Locale The locale is the first one found in: 1. the `locale` option of `createTranslator()`; 2. `<html data-symfony-ux-translator-locale="{{ app.request.locale }}">` (Symfony format, `de_AT`); 3. `<html lang="{{ app.request.locale|replace({'_': '-'}) }}">` (W3C format, `de-AT`); 4. the `defaultLocale` option, since Symfony UX 3.7+ (the dump exports `framework.default_locale`); 5. `en`. Change it at runtime with `setLocale()`; read it with `getLocale()`: ```javascript export const { trans, setLocale, getLocale } = translator; setLocale('de_AT'); ``` Fallbacks follow `localeFallbacks` from the dump, as in PHP (`de_AT` falls back to `de`). ## Missing Translations ```javascript const translator = createTranslator({ messages, localeFallbacks, defaultLocale, throwWhenNotFound: true, }); export const { trans, setThrowWhenNotFound } = translator; ``` Enable it in development or tests to catch keys missing from the dump. ## Dumping Translations are dumped on cache warmup. Since Symfony UX 3.1+, refresh only the JavaScript translations with: ```bash php bin/console ux:translator:warm-cache ``` ## Configuration ```yaml # config/packages/ux_translator.yaml (defaults) ux_translator: dump_directory: '%kernel.project_dir%/var/translations' # update assets/translator.js if changed dump_typescript: true domains: ~ # all domains keys_patterns: [] # all keys ``` AssetMapper never reads the TypeScript types, so skip them in production there: ```yaml when@prod: ux_translator: dump_typescript: false ``` Keep them with Encore or Reprise and TypeScript: the build type-checks against them. ## Gotchas - **Placeholder not replaced**: classic messages need the full key (`'%name%'`), plain `name` only works for ICU messages. - **Plural ignored**: pass `%count%` as a number for classic messages, `count` for ICU. - **New key returns the key itself**: the dump is stale or the key is filtered out. Run `ux:translator:warm-cache` and check `domains` / `keys_patterns`. - **Empty `var/translations/` on CI or in a Docker build stage**: run `cache:warmup` before the asset build, and copy the directory into the Node stage. - **Wrong locale**: set `data-symfony-ux-translator-locale` or `lang` on `<html>` from `app.request.locale`. - **Bundle too large**: filter with `domains` and `keys_patterns`. ## References - [Symfony UX package page](https://ux.symfony.com/translator) ([Markdown summary](https://ux.symfony.com/translator.md)) · [`symfony/ux-translator` on Packagist](https://packagist.org/packages/symfony/ux-translator). - Try the [JavaScript translation demo](https://ux.symfony.com/translator#demo). - For dumping catalogs, configuring locale and translating in JavaScript, see the [Symfony UX Translator documentation](https://symfony.com/bundles/ux-translator). ## See Also - **stimulus**: import `trans()` in a controller for client-side messages. - **ux-router**: same dump model for routes (`var/routes/`, `path()` in JavaScript).
Reviews (0)
No reviews yet.
Comments
Sign in to join the conversation.
No comments yet. Start the conversation.