String translation
As you develop more complex Magento stores, your clients will reach wider audiences. For this larger group of users, English may not be their first language. To account for this and to create a better user experience, it's crucial that we translate the strings in our template files.
Magento has made it simple for us to translate these strings by providing a PHP translation function __()
, which we can pass our strings through.
The translate function
The translate function is denoted with double underscore __()
and it takes an argument, which is the string that is to be translated.
Revisiting our welcome.phtml
file, we’ll wrap our text in a call to that translation function:
<h1><?= __('Hello world!') ?></h1>
This is the best practice when it comes to writing strings in template files. It allows Magento to find all these translatable strings and replace them with the corresponding translated text from a translation CSV file.
Add translations
Wrapping our strings in the translation function now allows these strings to be translated. Magento uses comma-separated values (CSV) text files for providing this translation capability. They are stored in a directory named i18n
, an abbreviation of the term 'Internationalization' where 18 stands for the number of letters between the first 'i' and the last 'n' in the word.
Let's create a translation file for French. In our module’s i18n
directory, we create a CSV file with the locale code as the filename. For French, the locale code is fr_FR
:
app/code/Macademy/Jumpstart/i18n/fr_FR.csv
In the fr_FR.csv
file, we need to implement the translation. To do this, we will replace "Hello world!" with "Bonjour le monde!". To write translations in a CSV file, follow the format: "Original Text","Translated Text". Make sure that the original text matches exactly with its appearance in the module or template file, including spaces and punctuation.
"Hello world!","Bonjour le monde!"
Save the changes and clear the cache. Now, if a user's locale is set to French, they will see "Bonjour le monde!" instead of "Hello world!".
Simple text changes
It’s also possible for us to use translation strings to easily change text strings. This is useful if you want to change just the text of a module or template file, without needing to override the entire file.
Since we are currently on the English store view, we can create a file with the local code en_US
:
app/code/Macademy/Jumpstart/i18n/en_US.csv
Now, we can use the exact same format as we did in our French translation file, but write our text update in the second column:
"Hello world!","Hi there!"
Now, when we refresh our page, we’ll see the updated text. Note that if you use this format, the value you place in the CSV file must exactly match the string as it is written in the module or template file — spaces and all.