Translation API - PHP Twig JavaScript | Drupal 8

Translation API - PHP Twig JavaScript

Submitted by editor on Thu, 09/30/2021 - 11:43

How to translate interface using drupal translation API ?

PHP Class using StringTranslationTrait

StringTranslationTrait allow to get t() and formatPlural() methods
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

@Translation("Text in context", context="Name of context")

In a Java Script (.js file)

Syntax: Drupal.t(str, args, options);
Drupal.t('May', {}, {context: "Long month name"});

In Twig templates

{{ '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 :

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.