Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Translation API - PHP Twig JavaScript

By editor , 30 September, 2021
Question

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

Tags

  • Drupal 8
  • Drupal 9
  • Translation
  • JavaScript
  • Twig
  • PHP

Comments

Plain text

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

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer