The t()
function is used for translating user-visible text in Drupal 9. It takes a string as input and returns a translated string.
Here's an example of how to use the t()
function in Drupal 9:
$message = t('Hello, world!');
In this example, the t()
function is used to translate the string "Hello, world!". If a translation for this string is available in the current language, the translated string will be returned. If a translation is not available, the original string will be returned.
By default, the t()
function uses the current language set for the site, as determined by Drupal's language negotiation system. However, you can also specify a specific language for the translation by passing a second argument to the function:
$message = t('Hello, world!', [], ['langcode' => 'fr']);
In this example, the t()
function is used to translate the string "Hello, world!" into French, regardless of the current language set for the site.
You can also include variables in the translated string by using placeholders:
$name = 'John';
$message = t('Hello, @name!', ['@name' => $name]);
In this example, the @name
placeholder is replaced with the value of the $name
variable in the translated string.
Finally, it's important to note that the t()
function should only be used for translating user-visible text, such as page titles, form labels, and error messages. It should not be used for translating code or configuration strings. For those use cases, you should use the @Translation()
service or the StringTranslationTrait
instead.
Additionally, in JavaScript and twig you can translate string in the following way:
let message = Drupal.t('Hello, world!');
let name = 'John';
let message = Drupal.t('Hello, @name!', {'@name': name});
// In this example, the @name placeholder is replaced with the
// value of the name variable in the translated string.
<!-- In twig -->
{% set message = 'Hello, world!'|t %}
<!-- More twig -->
{% set name = 'John' %}
{% set message = 'Hello, @name!'|t({'@name': name}) %}
<!--
In this example, the @name placeholder is replaced with the value
of the name variable in the translated string. Note that the t filter
takes an object as its argument, so you need to use parentheses
to pass in the object containing the placeholders.
-->