5.2. Translation and Sanitizing: t

The t function provides a dual purpose: It is the basis of Drupal's localization system and can also sanitize text that is displayed to users. This system was discussed in the introduction of Chapter 4, so the discussion here is a bit brief. If you are unclear on how to use it, please refer back to Chapter 4. Drupal's localization code works by creating a set of strings that contain placeholders so that translators have to translate the string only once, and it can be used for a variety of purposes. One example of this feature is the message shown to users when a new node is created: "Blog entry My Blog Entry has been created." Internally the excerpted code for that is:

$t_args = array('@type' => node_get_types('name', $node),
  '%title' => $node->title);
drupal_set_message(t('@type %title has been created.', $t_args));

There are three different types of placeholders for the t() function. This code snippet shows placeholders prefixed with @ and %, and there is a third placeholder not used in this example: !

  • Placeholders prefixed with @ or % sanitize the text before it is inserted into the string.

  • Using the @ prefix inserts the data without any decoration.

  • The % inserts the text after applying the "placeholders" theme function to the text, which wraps the text in HTML <em> tags by default.

  • Text prefixed with ! is not sanitized prior to insertion into the string and is suitable only for data that is known to be safe, such as a URL built with the l

Get Cracking Drupal®: A Drop in the Bucket now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.