Consuming strings in code
Last updated on
15 May 2025
The documentation has moved
New Location https://project.pages.drupalcode.org/string/
Impacts:
- Module developers
- Themers
The main aim is to provide developers with the ability to define interface text in their codebase using custom identifiers. The developers can also provide some meta data surrounding the strings if needed.
For example,
// Instead of doing this
t('Hello @name!', ['@name' => $name], ['context' => 'short greeting']);
// Do this
t('dashboard.greeting.short', ['@name' => $name]);
Where dashboard.greeting.short would be defined in dashboard.string.yml file as follows,
dashboard.greetings.short:
default: "Hello @name!"
Following is an sample string definitions used for examples on this page.
dashboard.greetings.short:
default: "Hello @name!"
placeholders:
- key: "@name"
type: string
comments:
- "The short greeting would be used on narrow width devices."
node.elapsed_time:
default: "@time ago"
placeholders:
- key: "@time"
type: string
comments.count:
default: "1 comment"
default_plural: "@count comments"
placeholders:
- key: "@count"
type: int
dashboard.title:
default: "Dashboard"
calendar_month.may:
default: "May"
msgctxt: 'Long month name'
welcome.message:
default: "Hello Earth!"
Usage
PHP code: using t()
Example: Formatting how long ago a node was created
Before
<?php
$ago = t('@time ago', array('@time' => \Drupal::service('date.formatter')->formatInterval((time() - $node->created) , 2));
?>After
<?php
$ago = t('node.elapsed_time', array('@time' => \Drupal::service('date.formatter')->formatInterval((time() - $node->created) , 2));
?>PHP code: using format_plural()
Example: Formatting total comment count plural text
Before
<?php
$output = \Drupal::translation()->formatPlural($node->comment_count, '1 comment', '@count comments');
?>After
<?php
// NOTE: same identifier is supplied as parameter for 2nd and 3rd argument.
$output = \Drupal::translation()->formatPlural($node->comment_count, 'comments.count', 'comments.count');
?>---
Inside a Class
Before
// ...
$string = $this->t('Dashboard');
// ...
After
// ...
$string = $this->t('dashboard.title');
// ...
Context in Drupal.t() and Drupal.formatPlural()
Before
Drupal.t('May', {}, {context: "Long month name"});After
Drupal.t('calendar_month.may', {}, {context: "Long month name"});Translation in Twig templates
Before
{{ 'Hello Earth!'|trans }}
{{ 'Hello Earth!'|t }}
{{ 'Hello @name!'|t({'@name': username}) }}After
{{ 'welcome.message'|trans }}
{{ 'welcome.message'|t }}
{{ 'dashboard.greetings.short'|t({'@name': username}) }}---
Help improve this page
Page status: No known problems
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion