Using Drupal's t (translate) functionPosted by: jimw, June 9th, 2010
Following extensive experience of using Drupal to deliver intenationalised and localised websites, there are a few fundamental issues that keep catching us out - one of the main ones is ensuring that we use Drupal's t function approriately.
Here's a simple 'gotcha':
<?php echo t('You are logged in as: ') . $username; ?>
<?php echo t('You are logged in as: %username', array('%username' => $username)); ?>
There are two main issues with the first approach:
- Use placeholders to insert dynamic content into strings wherever you can - in the first example it assumes that the correct place for the username is always at the end of the string - but let's say our translation is for 'Yoda-speak' where the translation migtht be "Logged in as %username you are.". And remember to use the most approriate prefix for the placeholder (i.e. '!', '@' or '%') to escape the value as applicable.
- A subtle one - it's not a good idea to rely on whitespace in the translated string - often translations will come back without the trailing space, so the username will appear straight after the colon rather than having a space separating it. Any sort of markup and layout inside strings should be avoided where possible.
So when using the t function, bear in mind how it might be best applied to help when populating translations.