Home > OS >  Symfony translation get value without parameter `%count%` or any other custom paramater
Symfony translation get value without parameter `%count%` or any other custom paramater

Time:10-11

I have list of months names in my translation config file

messages.en.yml:

basic:
   months:
      -
      - January
      - February
      - March
      - April
      - May
      - June
      - July
      - August
      - September
      - October
      - November
      - December

The translation works when I do this:

$this->translator->trans('basic.months.'.$month);

But the problem here is that php bin/console debug:translation en gives error that translation basic.months is missing.

How can I fix the issue without changing the config file ?

I can try this but

$this->translator->trans('basic.months', ['%count%' => $month]);

This code doesn't work and doesn't translate the message.

Thanks.

CodePudding user response:

The bin/console debug:translation scan all source files for static strings that contain message ids from your messages.en.yml file.

Your message id 'basic.months.'.$month is dynamic and that's why debug:translation could not detect it. Therefore it's hardly possible to fix error without changing the config file.

I suggest using icu message format:

$this->translator->trans('basic.months', ['month' =>  $month]);
# translations/messages intl-icu.en.yaml
basic:
  months: >-
    {month, select,
    1     {January}
    2     {February}
    3     {March}
    4     {April}
    5     {May}
    6     {June}
    7     {July}
    8     {August}
    9     {September}
    10    {October}
    11    {November}
    12    {December}
    other {}
    }

https://symfony.com/doc/current/translation/message_format.html#selecting-different-messages-based-on-a-condition

CodePudding user response:

So the problem was resolved by just doing this:

$transId = 'basic.months.'.$month;
$this->translator->trans($transId);

Now no debug errors are recorded and translations work as expected

  • Related