0

According to the documentation, we can use contexts with Drupal.t() since Drupal 8.

Drupal.t('May', {}, {context: "Long month name"}); works fine, but Drupal.t('May', {}, {context: "Abbreviated month name"}); doesn't translate May.

Why?

6
  • 2
    How are you determining it doesn't work?
    – Jaypan
    Commented Jan 20, 2022 at 16:20
  • In French it must return "Mai" ... but it returns "May".
    – fxa
    Commented Jan 20, 2022 at 16:24
  • Have you translated the string in the new context already?
    – leymannx
    Commented Jan 20, 2022 at 16:55
  • Of course... in php the t('May', {}, {context: "Abbreviated month name"}) works fine
    – fxa
    Commented Jan 20, 2022 at 17:07
  • 1
    Please provide more feedback, for example the code, expected output and actual output of what is currently working, the same for what is not working, and maybe a bit more info around it, that helps people here to help you.
    – berliner
    Commented Jan 20, 2022 at 17:11

1 Answer 1

0

For performance, Drupal do not load all translation string into Javascript. It need to specifically identify the translation string exists in a Javascript to load. Then the locale module will load your translation if the relevant JS file is loaded through the usual asset loading method (i.e. *.libraries.yml declaration).

To check if any of the translation text from the given context is loaded, you may check the window.drupalTranslations global object to see if it has loaded anything in your context.

Object.getPwnPropertyNames(druaplTranslations.strings);

Without any context loaded, the only available key of druaplTranslations.strings here is "":

Console result

This means the core locale module doesn't know that your module Javascript has a Drupal.t() call.

To manually fix this:

  1. Make sure that your Javascript file is not obscured so much that the Drupal.t() call is rewritten into something else.
  2. Run this with drush every time your Javascript has new / changed translation string:
    drush php:eval "_locale_parse_js_file('modules/custom/MODULENAME/js/path.to.your.js');"
    
  3. Clear cache:
    drush cr
    

(Also created #3460518 to see if there is a better way)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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