jimw's picture

Using Drupal's t (translate) function

Posted by:

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':

Wrong:
<?php echo t('You are logged in as: ') . $username; ?>

Right:
<?php echo t('You are logged in as: %username', array('%username' => $username)); ?>

There are two main issues with the first approach:

  1. 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.
  2. 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.

Your email address will not be published.

Digital Agency Norwich

About you

Alternatively why not give us a call.
We are always happy to talk

We would like to hear from you so please feel free to fill out the following details and any questions you may have and we will get back to you asap

+44(0)1603 727744