Symfony 4翻译组件按ID翻译失效问题咨询
$translator->trans($key) Uses <source> Instead of XLIFF id (and How to Fix It) Great question — I’ve run into this exact confusion with XLIFF and translation components like Symfony’s Translator before! Let’s break down why this happens and how to fix it.
Why This Happens
- Historical XLIFF conventions: Early versions of XLIFF (like 1.2) were widely adopted with the
<source>element serving as the natural translation key. Since it’s the actual source text, many tools and frameworks built their default behavior around this instead of theidattribute. - Component default configuration: Most translation libraries ship with XLIFF loaders that prioritize
<source>content by default. The documentation mentions "ID" as a general term, but in practice, the default loader is set to use the source text unless explicitly configured otherwise.
Fixes & Workarounds
You have two clear paths forward depending on whether you want to stick with using the id attribute or adapt to the default <source> behavior:
Option 1: Configure the Translator to Use XLIFF id as the Key
This aligns with your initial expectation of using the id attribute from your .xlf files. Taking Symfony as an example (the most common tool using XLIFF for translations):
- Update your translation configuration (e.g.,
config/packages/translation.yaml) to enable using theidattribute:framework: translator: default_path: '%kernel.project_dir%/translations' providers: xliff: xliff_loader: use_id_as_key: true - Ensure your
.xlffiles have properidattributes on each<trans-unit>:<trans-unit id="app.greeting.hello"> <source>Hello there!</source> <target>Bonjour !</target> </trans-unit> - Now you can call the translator with the
idvalue directly:$translator->trans('app.greeting.hello');
For other translation components, check their documentation for a similar setting (often named something like use_id_as_key or prefer_id_over_source).
Option 2: Adapt to Using <source> as the Key
If you prefer to work with the default behavior instead of changing configurations:
- Ensure the
$keyparameter in$translator->trans($key)exactly matches the text in the<source>element (including whitespace, capitalization, and special characters). - Example: If your
.xlfhas<source>Hello there!</source>, call:$translator->trans('Hello there!'); - Pro tip: Add the
idattribute to your<trans-unit>s anyway as a maintenance aid — it helps track translations even if you don’t use it as the key.
内容的提问来源于stack exchange,提问作者progonkpa

