As of Drupal 8, the string translation logic has been moved to a service and the translators that handle translations are now pluggable.
Core provides a few translators by default:
- CustomStrings Provides translation of custom strings set in settings.php
- FileTranslation Provides translation imported by po files
- StaticTranslation Provides simple translation by array of strings passed through its constructor
Locale module provides the full featured translation that it used to provide in Drupal 7 using locale's string storage and database caching.
Any module can provide additional translators by registering a service that implements the TranslatorInterface and is tagged as string_translator
. A priority can be set if you want your translator to fire before other translators. (higher priority means your translator will fire first)
Example:
In mymodule.service.yml
:
services:
string_translator.mymodule:
class: Drupal\mymodule\MyModuleTranslation
tags:
- { name: string_translator, priority: 5 }
All translators will fire sorted by priority until a translator that returns a translation is found.
Further improvements / API changes
- This also means that you can inject the translation service into your code, instead of relying on the global t() function, thus making your code unit-testable. (see https://drupal.org/node/2079611 exactly how)
The name of the new service is string_translation
and can be accessed by procedural code using Drupal::translation()
- Locale's module storage has been moved to a service as well, named locale.storage
and can be injected or accessed using the global Drupal object in procedural code:
D7
$storage = locale_storage();
D8
$storage = Drupal::service('locale.storage');