Jun 10, 2014

Better use of the t() function for translators

When coding the use of the t() function to indicate strings that may need to be translated, it's much better to prepare and pass a complete message rather than fragments of a message.

As pointed out by the source articles below, one compelling reason for doing so is that a single string that contains a complete message provides context that might otherwise be missing. Context is extremely important in understanding the words and phrases that are used so that both an accurate and a syntactically correct translation might be provided.

For example,
drupal_set_message(t('Enter your ' .
    l(t('account number'), '/mymodule/settings') .
    t('. There are also the ') .
    l(t('permissions'), '/permissions/module-mymodule') .
    t(' to set for specific roles.')),
As I understand it, the above code would result in five different strings to be translated that the translator might not readily know are really part of a single message.

1)  '. There are also the '
2)  ' to set for specific roles.'
3)  'Enter your '
4)  'permissions'
5)  'account number'

A second reason that the above code is problematic is that it assumes that the word order of the target languages is the same as in English. Not so! For instance, in Korean, the main verb of a sentence is normally at the very end. In Swahili, adjectives and other noun modifiers almost always come after the noun, not before. The five strings that are concatenated above are in a fixed order that cannot be changed except by modifying the code.

Here's a different way to code this to enable better translations.
drupal_set_message(t('Enter your ' .
    '<a href="@url_1">account number</a>.' .
    ' There are also the ' .
    '<a href="@url_2">permissions</a>' .
    ' to set for specific roles.',
    array('@url_1' => url('/mymodule/settings'),

              => url('/permissions/module-mymodule'))),
There is a single string and a single call to the t() function. The translator can change word order in any way appropriate, including the two HTML tags, whose targets are generated.

The downside is that the translator must be able to handle a bit of HTML since the string they will see is:
Enter your <a href="@url_1">account number</a>. There are also the <a href="@url_2">permissions</a> to set for specific roles.
See the sources below for more examples and discussion.

Update for Drupal 8, beta 1: function url() has been replaced. See http://optimizely-to-drupal-8.blogspot.com/2014/11/beta-1-released-more-changes.html


function  t

function  l

Dynamic strings with placeholders

1 comment:

  1. Good point! The next time I use t() I'll this in mind.