2

I've created a custom module, that uses templates with hard coded strings. I've created the .pot and .po files and included them my module's YML file. The Twig tempatles translate those strings using the |t operator. This works fine.

Now I've run into a problem: My module offers button to book an accommodation, which clashes with Drupal's book (to read) module. In the german translation those two words are completely different.

I've got two questions:

  1. How to I provide a translation for the book verb in my module, in a way that it doesn't clash with the book module.
  2. How to I use the tell Twig to use the correct book string from my module?

E.g. this template code
First I want to {{ 'book'|t('context_accomodation') }} a hotel room and when I arrive I want to read a {{ 'book'|t('context_reading') }}

should render in english
First I want to book a hotel room and when I arrive I want to read a book

and should render in german
First I want to buchen a hotel room and when I arrive I want to read a Buch

2

Drupal does have an answer to this problem, at least if it's your own code where you need to make that distinction. It's called context.

In the PO file, add a msgctxt line

# an explanatory comment line for your translator
msgctxt "Accomodation"
msgid "book"
msgstr "buchen"

In PHP, it works like this:

<?php
t('book', [], ['context' => 'Accomodation']);
?>

In twig, it should go like this:

{{ 'book'|t({}, {'context': 'Accomodation'}) }}

The problem with this approach is that the developer needs to be aware that a certain word might have a multiple context specific translations in another language that he most likely doesn't know. But for your specific scenario, it should work fine.

  • Google told me there is a msgctext for PO files e.g. msgctxt "Accodmodation" , I guess Drupal/Twig will be using this. Need to test when back in office. – Hudri Oct 3 '18 at 20:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.