In many Symfony applications, certain text fragments - such as the application name, company name, or version number - are reused across multiple translation strings. Passing these values manually every time can quickly become repetitive and error-prone. Symfony provides a clean solution by allowing you to define global translation parameters that are automatically available to all translation messages. This tutorial explains how to define global translation parameters in Symfony 8 application.
Let's start by defining translation messages that contain dynamic parameters.
translations/messages.en.yaml
welcome_title: Welcome to %app_name%
powered_by: Powered by {company}
Here, %app_name% and {company} are parameters that will be replaced at runtime.
Instead of passing these values every time when translating messages, you can register them globally in the configuration file.
config/packages/translation.yaml
framework:
# ...
translator:
# ...
globals:
'%%app_name%%': 'My App'
'{company}': 'My Company'
Note: When using %...% placeholders, you must escape them with double percent signs (%%) in the configuration file.
Once defined, these parameters are automatically injected into all translation messages. For example, you can now use the trans filter in Twig without explicitly passing parameters.
templates/test/index.html.twig
{{ 'welcome_title'|trans }} {# Welcome to My App #}
{{ 'powered_by'|trans }} {# Powered by My Company #}
{{ 'welcome_title'|trans({'%app_name%': 'ABC App'}) }} {# Welcome to ABC App #}
{{ 'powered_by'|trans({'{company}': 'ABC Company'}) }} {# Powered by ABC Company #}
Global parameters are convenient defaults, but you can still override them on a per-message basis when needed. Any parameters passed directly to trans take precedence over the globally configured ones.
Leave a Comment
Cancel reply