How to translate interface using drupal translation API ?
PHP Class using StringTranslationTrait
StringTranslationTrait allow to get t() and formatPlural() methods
Example:
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
class MyClass {
use StringTranslationTrait;
/**
* Constructs a MyClass object.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation service.
*/
public function __construct(TranslationInterface $string_translation) {
// You can skip injecting this service, the trait will fall back to \Drupal::translation()
// but it is recommended to do so, for easier testability,
$this->stringTranslation = $string_translation;
$string = $this->t('Something');
}
}
In annotation text
Examples:
@Translation("File")
@Translation("Text in context", context="Name of context")
In a Java Script (.js file)
Syntax: Drupal.t(str, args, options);
Examples:
Drupal.t('May');
Drupal.formatPlural('May');
Drupal.t('May', {}, {context: "Long month name"});
In Twig templates
Examples:
{{ 'Hello Earth.'|trans }}
{{ 'Hello Earth.'|t }}
{{ 'Hello @username.'|t({'@username': username}) }}
{% trans %}Hello {{username}}.{% endtrans %}
{% set labelText = '@action for @name'|t({'@action': actionText|default('Close')|t,'@name': nameText}) %}
Doc : https://www.drupal.org/docs/8/api/translation-api/overview
Comments