Use t() function in php

Ready for review -- AWAITING PEER REVIEW

Drupal's t() function is used to allow text to be translated. This is very helpful in the i18n of your Drupal site, so in this lesson you will learn how to use the t() function for PHP.

  • Intall the multilingual modules on a D8 site
  • Complete the previous lessons in this ladder

1. Download and install the example module on your D8 site. You can find the example module here. In this lesson, you will use the hello module.

2. Navigate to the /modules/hello/lib/Drupal/hello/Controller directory and open the HelloController.php file.

3. The line
'#markup' => 'Hello World!',
displays text to the user. Because of this, it should be passed through Drupal's t() function so it can be translated. Change the line to
'#markup' => t('Hello World!'),

4. On your Drupal site, go to /en/hello and you should see a page containing the following text.

5. To allow the text to be translated, you must first view the page in another language. In the previous lessons, Spanish was used so if you followed those lessons navigate to /es/hello.

6. Uh oh. The text is still in English! Unfortunately, your site isn't magical and doesn't automatically translate text into another language. You need to do this manually. Go to Configuration > Languages and click on Spanish under Interface Translation.

7. Search for the phrase "Hello". The search is case sensitive

8. Change "Hello" to "Hola" and "Hello World!" to "¡Hola Mundo!"

9. Navigate back to /es/hello and the page will have been translated.

Congratulations. You have just learned how to use Drupal's t() function for PHP!