Module Development

Output Translatable Strings for Drupal 8, 9, 10, and 11

It's a Drupal best practice to always use Drupal's internationalization utilities for any user interface strings in your code. This includes the PHP t() function and StringTranslationTrait trait, the Twig t filter, and the JavaScript Drupal.t() function. This makes it possible for our module's interface to be localized.

In this tutorial, we'll:

  • Edit the WeatherPage controller and use the t() method from the StringTranslationTrait trait for all UI strings.
  • Update the weather-page.html.twig template file to use the Twig t filter.
  • Modify the JavaScript in our forecast.js code to use the Drupal.t() function for UI strings.

By the end of this tutorial you should be able to update the PHP, Twig, and JavaScript code in your module to ensure that any user interface strings they output are translatable.

Drupal Module Developer Guide