Today there will be a small note on the topic - how to add a translation file to a custom module in drupal 8/9, so that the text values of the module can be translated in the translation system of the interface of the drupal engine itself. This can be one way to make it easier to launch a multilingual website.

First you need to add in the info.yml file of our module at the end of the line

project: module_name
'interface translation project': module_name
'interface translation server pattern': modules/custom/module_name/translations/module_name-uk.po


  • module_name - the name of our custom module
  • module_name-uk.po - Ukrainian translation file, since Ukrainian language code and ID in drupal - uk

After that, in the folder of our module, create a translations folder and inside it module_name-uk.po

I was too lazy to look for all the details on the translation file, the main thing is that there should be a line with the original and a line with the translation, which begin with msgid and msgtr. Comments can be added with a hash at the beginning. For example

# Text for button
msgid "Call You?"
msgstr "Передзвонити Вам?"

Now we need to somehow indicate that these particular strings need to be translated in the template or module file.

If the text for translation is set in the twig module template, then in the right place we add

{{ 'Call You?'|t }}

If we set a text value in the module or src php file, then the entry will be something like the following

$button[] = [
   'name'   =>   $this->t('Call You?'),

After that, we clear the cache and go to the admin/reports/translations section, where we click on the link for manually checking translations. After checking, the system should "see" that there is a new translation for our module and below the buttons for updating translations will appear. After the update, we go to the translation of the admin /config/regional/translate interface and use the filters to try to search for our strings for translation in the languages we need. Now the translation language of this added line can be edited from the admin panel.

upd. a small addition of information - to work with languages it is better to transfer all the executable code from the .module file to the src-plugin-block .php file, since in the first case, the data is cached and incorrect results will be displayed.

upd2. also, to display the current interface language in the module

$langcode = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();

it is necessary at the beginning of the block connection to add the connection using interface variables

use Drupal\Core\Language\LanguageInterface;