The |trans modifier translates string values using a TranslatorInterface implementation.
- String values with
|transpipe are passed through the translator - Non-string values delegate to the next modifier
- Missing translations return the original key unchanged
By default, uses a BypassTranslator that returns the original input:
use Respect\StringFormatter\PlaceholderFormatter;
$formatter = new PlaceholderFormatter(['message' => 'hello']);
echo $formatter->format('{{message|trans}}');
// Output: helloInstall symfony/translation and inject a real translator:
use Respect\StringFormatter\PlaceholderFormatter;
use Respect\StringFormatter\Modifiers\TransModifier;
use Respect\StringFormatter\Modifiers\StringPassthroughModifier;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\Loader\ArrayLoader;
$translator = new Translator('en');
$translator->addLoader('array', new ArrayLoader());
$translator->addResource('array', ['greeting' => 'Hello World'], 'en');
$formatter = new PlaceholderFormatter(
['key' => 'greeting'],
new TransModifier(new StringifyModifier(), $translator),
);
echo $formatter->format('{{key|trans}}');
// Output: Hello World| Parameters | Template | Output |
|---|---|---|
['msg' => 'hello'] |
{{msg|trans}} |
hello |
['key' => 'greeting'] |
{{key|trans}} |
Hello World |