views:

233

answers:

2

I'm reading Pro Drupal Development, Second Edition. It says that the following is necessary:

t("Your favorite color is !color", array('!color' => "$color"));

But it also says that the ! placeholder means that no transformation will be done on the string. So why not just:

t("Your favorite color is $color");

Thanks.

+7  A: 

t() is used to look up a translation of the enclosed string. If you have variable content directly in that string ($color in your example), the translation lookup will fail for any new content encountered and not yet translated. The placeholders allow translators to translate only the fixed part of the string and still allow injection of variable content.

The modifiers '!','%','@' just give you some more control over how the insertion takes place, with '!' meaning that the string will be inserted as is.

The most obvious example would be with numbers:

If you have

t("Number $count");

and you call it several times with different numbers, say 1,2,3, each time t() would look for a different translation for a different string:

  1. t('Number 1')
  2. t('Number 2')
  3. t('Number 3')

whereas with

t('Number !count', array('!count' => $count);

it would only look for one translation, injecting the number 'as is' into that!

An added benefit is that the translator can place the placeholder in a different position that fits the usage of the target language by providing, e.g. '!count whatever' as the translation string. With the above example, this would result in:

  1. '1 whatever'
  2. '2 whatever'
  3. '3 whatever'

Using '%' would surround the placeholder with <em> tags for highlighting, '@' would run it through check_plain() to escape markup.

Henrik Opel
A: 

The first argument of t() is a literal string; a function call as t("Your favorite color is $color") doesn't pass to the function a literal string, and the script to extract the strings to translate would not be able to extract a string to translate. Actually, the extraction script would extract "Your favorite color is $color" (to notice the variable has been not replaced in the string), but that is not the string that at runtime would be passed to t().

kiamlaluno