Translations

Translations

The term “internationalization” (often abbreviated i18n) refers to the process of abstracting strings and other locale-specific pieces out of your application into a layer where they can be translated and converted based on the user’s locale (i.e. language and country). For text, this means wrapping each with a function capable of translating the text (or “message”) into the language of the user:

  1. // text will *always* print out in English
  2. echo 'Hello World';
  3. // text can be translated into the end-user's language or
  4. // default to English
  5. echo $translator->trans('Hello World');

Note

The term locale refers roughly to the user’s language and country. It can be any string that your application uses to manage translations and other format differences (e.g. currency format). The ISO 639-1 language code, an underscore (_), then the ISO 3166-1 alpha-2 country code (e.g. fr_FR for French/France) is recommended.

The translation process has several steps:

  1. Enable and configure Symfony’s translation service;
  2. Abstract strings (i.e. “messages”) by wrapping them in calls to the Translator (”Basic Translation”);
  3. Create translation resources/files for each supported locale that translate each message in the application;
  4. Determine, set and manage the user’s locale for the request and optionally on the user’s entire session.

Installation

First, run this command to install the translator before using it:

  1. $ composer require symfony/translation

Configuration

The previous command creates an initial config file where you can define the default locale of the application and the directory where the translation files are located:

  • YAML

    1. # config/packages/translation.yaml
    2. framework:
    3. default_locale: 'en'
    4. translator:
    5. default_path: '%kernel.project_dir%/translations'
  • XML

    1. <!-- config/packages/translation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/symfony
    9. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    10. <framework:config default-locale="en">
    11. <framework:translator>
    12. <framework:default-path>'%kernel.project_dir%/translations'</framework:default-path>
    13. <!-- ... -->
    14. </framework:translator>
    15. </framework:config>
    16. </container>
  • PHP

    1. // config/packages/translation.php
    2. use Symfony\Config\FrameworkConfig;
    3. return static function (FrameworkConfig $framework) {
    4. // ...
    5. $framework
    6. ->defaultLocale('en')
    7. ->translator()
    8. ->defaultPath('%kernel.project_dir%/translations')
    9. ;
    10. };

The locale used in translations is the one stored on the request. This is typically set via a _locale attribute on your routes (see The Locale and the URL).

Basic Translation

Translation of text is done through the translator service (Symfony\Component\Translation\Translator). To translate a block of text (called a message), use the trans() method. Suppose, for example, that you’re translating a static message from inside a controller:

  1. // ...
  2. use Symfony\Contracts\Translation\TranslatorInterface;
  3. public function index(TranslatorInterface $translator)
  4. {
  5. $translated = $translator->trans('Symfony is great');
  6. // ...
  7. }

When this code is run, Symfony will attempt to translate the message “Symfony is great” based on the locale of the user. For this to work, you need to tell Symfony how to translate the message via a “translation resource”, which is usually a file that contains a collection of translations for a given locale. This “dictionary” of translations can be created in several different formats:

  • YAML

    1. # translations/messages.fr.yaml
    2. Symfony is great: J'aime Symfony
  • XML

    1. <!-- translations/messages.fr.xlf -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    4. <file source-language="en" datatype="plaintext" original="file.ext">
    5. <body>
    6. <trans-unit id="symfony_is_great">
    7. <source>Symfony is great</source>
    8. <target>J'aime Symfony</target>
    9. </trans-unit>
    10. </body>
    11. </file>
    12. </xliff>
  • PHP

    1. // translations/messages.fr.php
    2. return [
    3. 'Symfony is great' => "J'aime Symfony",
    4. ];

For information on where these files should be located, see Translation Resource/File Names and Locations.

Now, if the language of the user’s locale is French (e.g. fr_FR or fr_BE), the message will be translated into J'aime Symfony. You can also translate the message inside your templates.

Using Real or Keyword Messages

This example illustrates the two different philosophies when creating messages to be translated:

  1. $translator->trans('Symfony is great');
  2. $translator->trans('symfony.great');

In the first method, messages are written in the language of the default locale (English in this case). That message is then used as the “id” when creating translations.

In the second method, messages are actually “keywords” that convey the idea of the message. The keyword message is then used as the “id” for any translations. In this case, translations must be made for the default locale (i.e. to translate symfony.great to Symfony is great).

The second method is handy because the message key won’t need to be changed in every translation file if you decide that the message should actually read “Symfony is really great” in the default locale.

The choice of which method to use is entirely up to you, but the “keyword” format is often recommended for multi-language applications, whereas for shared bundles that contain translation resources we recommend the real message, so your application can choose to disable the translator layer and you will see a readable message.

Additionally, the php and yaml file formats support nested ids to avoid repeating yourself if you use keywords instead of real text for your ids:

  • YAML

    1. symfony:
    2. is:
    3. # id is symfony.is.great
    4. great: Symfony is great
    5. # id is symfony.is.amazing
    6. amazing: Symfony is amazing
    7. has:
    8. # id is symfony.has.bundles
    9. bundles: Symfony has bundles
    10. user:
    11. # id is user.login
    12. login: Login
  • PHP

    1. [
    2. 'symfony' => [
    3. 'is' => [
    4. // id is symfony.is.great
    5. 'great' => 'Symfony is great',
    6. // id is symfony.is.amazing
    7. 'amazing' => 'Symfony is amazing',
    8. ],
    9. 'has' => [
    10. // id is symfony.has.bundles
    11. 'bundles' => 'Symfony has bundles',
    12. ],
    13. ],
    14. 'user' => [
    15. // id is user.login
    16. 'login' => 'Login',
    17. ],
    18. ];

The Translation Process

To actually translate the message, Symfony uses the following process when using the `trans() method:

  1. The locale of the current user, which is stored on the request is determined;
  2. A catalog (e.g. big collection) of translated messages is loaded from translation resources defined for the locale (e.g. fr_FR). Messages from the fallback locale are also loaded and added to the catalog if they don’t already exist. The end result is a large “dictionary” of translations. This catalog is cached in production to minimize performance impact.
  3. If the message is located in the catalog, the translation is returned. If not, the translator returns the original message.

Tip

When translating strings that are not in the default domain (messages), you must specify the domain as the third argument of `trans():

  1. $translator->trans('Symfony is great', [], 'admin');

Message Format

Sometimes, a message containing a variable needs to be translated:

  1. // ...
  2. $translated = $translator->trans('Hello '.$name);

However, creating a translation for this string is impossible since the translator will try to look up the message including the variable portions (e.g. “Hello Ryan” or “Hello Fabien”).

Another complication is when you have translations that may or may not be plural, based on some variable:

  1. There is one apple.
  2. There are 5 apples.

To manage these situations, Symfony follows the ICU MessageFormat syntax by using PHP’s MessageFormatter class. Read more about this in How to Translate Messages using the ICU MessageFormat.

Translatable Objects

New in version 5.2: Translatable objects were introduced in Symfony 5.2.

Sometimes translating contents in templates is cumbersome because you need the original message, the translation parameters and the translation domain for each content. Making the translation in the controller or services simplifies your templates, but requires injecting the translator service in different parts of your application and mocking it in your tests.

Instead of translating a string at the time of creation, you can use a “translatable object”, which is an instance of the Symfony\Component\Translation\TranslatableMessage class. This object stores all the information needed to fully translate its contents when needed:

  1. use Symfony\Component\Translation\TranslatableMessage;
  2. // the first argument is required and it's the original message
  3. $message = new TranslatableMessage('Symfony is great!');
  4. // the optional second argument defines the translation parameters and
  5. // the optional third argument is the translation domain
  6. $status = new TranslatableMessage('order.status', ['%status%' => $order->getStatus()], 'store');

Templates are now much simpler because you can pass translatable objects to the trans filter:

  1. <h1>{{ message|trans }}</h1>
  2. <p>{{ status|trans }}</p>

Tip

There’s also a function called t(), available both in Twig and PHP, as a shortcut to create translatable objects.

Translations in Templates

Most of the time, translation occurs in templates. Symfony provides native support for both Twig and PHP templates.

Using Twig Tags

Symfony provides a specialized Twig tag trans to help with message translation of static blocks of text:

  1. {% trans %}Hello %name%{% endtrans %}

Caution

The %var% notation of placeholders is required when translating in Twig templates using the tag.

Tip

If you need to use the percent character (%) in a string, escape it by doubling it: {% trans %}Percent: %percent%%%{% endtrans %}

You can also specify the message domain and pass some additional variables:

  1. {% trans with {'%name%': 'Fabien'} from 'app' %}Hello %name%{% endtrans %}
  2. {% trans with {'%name%': 'Fabien'} from 'app' into 'fr' %}Hello %name%{% endtrans %}

Using Twig Filters

The trans filter can be used to translate variable texts and complex expressions:

  1. {{ message|trans }}
  2. {{ message|trans({'%name%': 'Fabien'}, 'app') }}

Tip

Using the translation tags or filters have the same effect, but with one subtle difference: automatic output escaping is only applied to translations using a filter. In other words, if you need to be sure that your translated message is not output escaped, you must apply the raw filter after the translation filter:

  1. {# text translated between tags is never escaped #}
  2. {% trans %}
  3. <h3>foo</h3>
  4. {% endtrans %}
  5. {% set message = '<h3>foo</h3>' %}
  6. {# strings and variables translated via a filter are escaped by default #}
  7. {{ message|trans|raw }}
  8. {{ '<h3>bar</h3>'|trans|raw }}

Tip

You can set the translation domain for an entire Twig template with a single tag:

  1. {% trans_default_domain 'app' %}

Note that this only influences the current template, not any “included” template (in order to avoid side effects).

PHP Templates

The translator service is accessible in PHP templates through the translator helper:

  1. <?= $view['translator']->trans('Symfony is great') ?>

Forcing the Translator Locale

When translating a message, the translator uses the specified locale or the fallback locale if necessary. You can also manually specify the locale to use for translation:

  1. $translator->trans(
  2. 'Symfony is great',
  3. [],
  4. 'messages',
  5. 'fr_FR'
  6. );

Extracting Translation Contents and Updating Catalogs Automatically

The most time-consuming tasks when translating an application is to extract all the template contents to be translated and to keep all the translation files in sync. Symfony includes a command called translation:update that helps you with these tasks:

  1. # shows all the messages that should be translated for the French language
  2. $ php bin/console translation:update --dump-messages fr
  3. # updates the French translation files with the missing strings for that locale
  4. $ php bin/console translation:update --force fr
  5. # check out the command help to see its options (prefix, output format, domain, sorting, etc.)
  6. $ php bin/console translation:update --help

The translation:update command looks for missing translations in:

  • Templates stored in the templates/ directory (or any other directory defined in the twig.default_path and twig.paths config options);
  • Any PHP file/class that injects or autowires the translator service and makes calls to the `trans() method.
  • Any PHP file/class stored in the src/ directory that creates Translatable Objects using the constructor or the t() method or calls thetrans() method.

New in version 5.3: Support for extracting Translatable objects has been introduced in Symfony 5.3.

Translation Resource/File Names and Locations

Symfony looks for message files (i.e. translations) in the following default locations:

  • the translations/ directory (at the root of the project);
  • the Resources/translations/ directory inside of any bundle.

The locations are listed here with the highest priority first. That is, you can override the translation messages of a bundle in the first directory.

The override mechanism works at a key level: only the overridden keys need to be listed in a higher priority message file. When a key is not found in a message file, the translator will automatically fall back to the lower priority message files.

The filename of the translation files is also important: each message file must be named according to the following path: domain.locale.loader:

  • domain: Domains are a way to organize messages into groups. Unless parts of the application are explicitly separated from each other, it is recommended to only use the default messages domain (e.g. messages.en.yaml).
  • locale: The locale that the translations are for (e.g. en_GB, en, etc);
  • loader: How Symfony should load and parse the file (e.g. xlf, php, yaml, etc).

The loader can be the name of any registered loader. By default, Symfony provides many loaders:

  • .yaml: YAML file
  • .xlf: XLIFF file;
  • .php: Returning a PHP array;
  • .csv: CSV file;
  • .json: JSON file;
  • .ini: INI file;
  • .dat, .res: ICU resource bundle;
  • .mo: Machine object format;
  • .po: Portable object format;
  • .qt: QT Translations XML file;

The choice of which loader to use is entirely up to you and is a matter of taste. The recommended option is to use YAML for simple projects and use XLIFF if you’re generating translations with specialized programs or teams.

Caution

Each time you create a new message catalog (or install a bundle that includes a translation catalog), be sure to clear your cache so that Symfony can discover the new translation resources:

  1. $ php bin/console cache:clear

Note

You can add other directories with the paths option in the configuration:

  • YAML

    1. # config/packages/translation.yaml
    2. framework:
    3. translator:
    4. paths:
    5. - '%kernel.project_dir%/custom/path/to/translations'
  • XML

    1. <!-- config/packages/translation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:framework="http://symfony.com/schema/dic/symfony"
    5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-Instance"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/symfony
    9. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    10. <framework:config>
    11. <framework:translator>
    12. <framework:path>%kernel.project_dir%/custom/path/to/translations</framework:path>
    13. </framework:translator>
    14. </framework:config>
    15. </container>
  • PHP

    1. // config/packages/translation.php
    2. use Symfony\Config\FrameworkConfig;
    3. return static function (FrameworkConfig $framework) {
    4. $framework->translator()
    5. ->paths(['%kernel.project_dir%/custom/path/to/translations'])
    6. ;
    7. };

Note

You can also store translations in a database, or any other storage by providing a custom class implementing the Symfony\Component\Translation\Loader\LoaderInterface interface. See the translation.loader tag for more information.

Translation Providers

New in version 5.3: Translation providers were introduced in Symfony 5.3 as an experimental feature.

When using external translators to translate your application, you must send them the new contents to translate frequently and merge the results back in the application.

Instead of doing this manually, Symfony provides integration with several third-party translation services (e.g. Crowdin or Lokalise). You can upload and download (called “push” and “pull”) translations to/from these services and merge the results automatically in the application.

Installing and Configuring a Third Party Provider

Before pushing/pulling translations to a third-party provider, you must install the package that provides integration with that provider:

ProviderInstall with
Crowdincomposer require symfony/crowdin-translation-provider
Loco (localise.biz)composer require symfony/loco-translation-provider
Lokalisecomposer require symfony/lokalise-translation-provider

Each library includes a Symfony Flex recipe that will add a configuration example to your .env file. For example, suppose you want to use Loco. First, install it:

  1. $ composer require symfony/loco-translation-provider

You’ll now have a new line in your .env file that you can uncomment:

  1. # .env
  2. LOCO_DSN=loco://[email protected]

The LOCO_DSN isn’t a real address: it’s a convenient format that offloads most of the configuration work to Symfony. The loco scheme activates the Loco provider that you just installed, which knows all about how to push and pull translations via Loco. The only part you need to change is the API_KEY placeholder.

This table shows the full list of available DSN formats for each provider:

ProviderDSN
Crowdincrowdin://PROJECT_ID:API_TOKEN@ORGANIZATION_DOMAIN.default
Loco (localise.biz)loco://API_KEY@default
Lokaliselokalise://PROJECT_ID:API_KEY@default

To enable a translation provider, add the correct DSN in your .env file and configure the providers option:

  • YAML

    1. # config/packages/translation.yaml
    2. framework:
    3. translator:
    4. providers:
    5. loco:
    6. dsn: '%env(LOCO_DSN)%'
    7. domains: ['messages']
    8. locales: ['en', 'fr']
  • XML

    1. <!-- config/packages/translation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/symfony
    9. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    10. <framework:config>
    11. <framework:translator>
    12. <framework:provider name="loco" dsn="%env(LOCO_DSN)%">
    13. <framework:domain>messages</framework:domain>
    14. <!-- ... -->
    15. <framework:locale>en</framework:locale>
    16. <framework:locale>fr</framework:locale>
    17. <!-- ... -->
    18. </framework:provider>
    19. </framework:translator>
    20. </framework:config>
    21. </container>
  • PHP

    1. # config/packages/translation.php
    2. $container->loadFromExtension('framework', [
    3. 'translator' => [
    4. 'providers' => [
    5. 'loco' => [
    6. 'dsn' => '%env(LOCO_DSN)%',
    7. 'domains' => ['messages'],
    8. 'locales' => ['en', 'fr'],
    9. ],
    10. ],
    11. ],
    12. ]);

Tip

If you use Lokalise as provider and a locale format following the ISO 639-1 (e.g., “en” or “fr”), you have to set the Custom Language Name setting in Lokalise for each of your locales, in order to override the default value (which follow the ISO 639-1 succeeded by a sub-code in capital letters that specifies the national variety (e.g., “GB” or “US” according to ISO 3166-1 alpha-2)).

Pushing and Pulling Translations

After configuring the credentials to access the translation provider, you can now use the following commands to push (upload) and pull (download) translations:

  1. # push all local translations to the Loco provider for the locales and domains
  2. # configured in config/packages/translation.yaml file.
  3. # it will update existing translations already on the provider.
  4. $ php bin/console translation:push loco --force
  5. # push new local translations to the Loco provider for the French locale
  6. # and the validators domain.
  7. # it will **not** update existing translations already on the provider.
  8. $ php bin/console translation:push loco --locales fr --domain validators
  9. # push new local translations and delete provider's translations that not
  10. # exists anymore in local files for the French locale and the validators domain.
  11. # it will **not** update existing translations already on the provider.
  12. $ php bin/console translation:push loco --delete-missing --locales fr --domain validators
  13. # check out the command help to see its options (format, domains, locales, etc.)
  14. $ php bin/console translation:push --help
  1. # pull all provider's translations to local files for the locales and domains
  2. # configured in config/packages/translation.yaml file.
  3. # it will overwrite completely your local files.
  4. $ php bin/console translation:pull loco --force
  5. # pull new translations from the Loco provider to local files for the French
  6. # locale and the validators domain.
  7. # it will **not** overwrite your local files, only add new translations.
  8. $ php bin/console translation:pull loco --locales fr --domain validators
  9. # check out the command help to see its options (format, domains, locales, intl-icu, etc.)
  10. $ php bin/console translation:pull --help

Handling the User’s Locale

Translating happens based on the user’s locale. Read How to Work with the User’s Locale to learn more about how to handle it.

Fallback Translation Locales

Imagine that the user’s locale is es_AR and that you’re translating the key Symfony is great. To find the Spanish translation, Symfony actually checks translation resources for several locales:

  1. First, Symfony looks for the translation in a es_AR (Argentinean Spanish) translation resource (e.g. messages.es_AR.yaml);

  2. If it wasn’t found, Symfony looks for the translation in the parent locale, which is automatically defined only for some locales. In this example, the parent locale is es_419 (Latin American Spanish);

  3. If it wasn’t found, Symfony looks for the translation in a es (Spanish) translation resource (e.g. messages.es.yaml);

  4. If the translation still isn’t found, Symfony uses the fallbacks option, which can be configured as follows:

    • YAML

      1. # config/packages/translation.yaml
      2. framework:
      3. translator:
      4. fallbacks: ['en']
      5. # ...
    • XML

      1. <!-- config/packages/translation.xml -->
      2. <?xml version="1.0" encoding="UTF-8" ?>
      3. <container xmlns="http://symfony.com/schema/dic/services"
      4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      5. xmlns:framework="http://symfony.com/schema/dic/symfony"
      6. xsi:schemaLocation="http://symfony.com/schema/dic/services
      7. https://symfony.com/schema/dic/services/services-1.0.xsd
      8. http://symfony.com/schema/dic/symfony
      9. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
      10. <framework:config>
      11. <framework:translator>
      12. <framework:fallback>en</framework:fallback>
      13. <!-- ... -->
      14. </framework:translator>
      15. </framework:config>
      16. </container>
    • PHP

      1. // config/packages/translation.php
      2. use Symfony\Config\FrameworkConfig;
      3. return static function (FrameworkConfig $framework) {
      4. // ...
      5. $framework->translator()
      6. ->fallbacks(['en'])
      7. ;
      8. };

Note

When Symfony can’t find a translation in the given locale, it will add the missing translation to the log file. For details, see logging.

Translating Database Content

The translation of database content should be handled by Doctrine through the Translatable Extension or the Translatable Behavior (PHP 5.4+). For more information, see the documentation for these libraries.

Debugging Translations

When you work with many translation messages in different languages, it can be hard to keep track which translations are missing and which are not used anymore. Read How to Find Missing or Unused Translation Messages to find out how to identify these messages.

Summary

With the Symfony Translation component, creating an internationalized application no longer needs to be a painful process and boils down to these steps:

  • Abstract messages in your application by wrapping each in the trans() method;
  • Translate each message into multiple locales by creating translation message files. Symfony discovers and processes each file because its name follows a specific convention;
  • Manage the user’s locale, which is stored on the request, but can also be set on the user’s session.

Learn more

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.