How to Translate Messages using the ICU MessageFormat

How to Translate Messages using the ICU MessageFormat

New in version 4.2: Support for ICU MessageFormat was introduced in Symfony 4.2.

Messages (i.e. strings) in applications are almost never completely static. They contain variables or other complex logic like pluralization. In order to handle this, the Translator component supports the ICU MessageFormat syntax.

Tip

You can test out examples of the ICU MessageFormatter in this online editor.

Using the ICU Message Format

In order to use the ICU Message Format, the message domain has to be suffixed with +intl-icu:

Normal file nameICU Message Format filename
messages.en.yamlmessages+intl-icu.en.yaml
messages.fr_FR.xlfmessages+intl-icu.fr_FR.xlf
admin.en.yamladmin+intl-icu.en.yaml

All messages in this file will now be processed by the [MessageFormatter](https://www.php.net/manual/en/class.messageformatter.php "MessageFormatter") during translation.

Message Placeholders

The basic usage of the MessageFormat allows you to use placeholders (called arguments in ICU MessageFormat) in your messages:

  • YAML

    1. # translations/messages+intl-icu.en.yaml
    2. say_hello: 'Hello {name}!'
  • XML

    1. <!-- translations/messages+intl-icu.en.xlf -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    4. <file source-language="en" datatype="plaintext" original="file.ext">
    5. <body>
    6. <trans-unit id="say_hello">
    7. <source>say_hello</source>
    8. <target>Hello {name}!</target>
    9. </trans-unit>
    10. </body>
    11. </file>
    12. </xliff>
  • PHP

    1. // translations/messages+intl-icu.en.php
    2. return [
    3. 'say_hello' => "Hello {name}!",
    4. ];

Caution

In the previous translation format, placeholders were often wrapped in % (e.g. %name%). This % character is no longer valid with the ICU MessageFormat syntax, so you must rename your parameters if you are upgrading from the previous format.

Everything within the curly braces ({...}) is processed by the formatter and replaced by its placeholder:

  1. // prints "Hello Fabien!"
  2. echo $translator->trans('say_hello', ['name' => 'Fabien']);
  3. // prints "Hello Symfony!"
  4. echo $translator->trans('say_hello', ['name' => 'Symfony']);

Selecting Different Messages Based on a Condition

The curly brace syntax allows to “modify” the output of the variable. One of these functions is the select function. It acts like PHP’s switch statement and allows to use different strings based on the value of the variable. A typical usage of this is gender:

  • YAML

    1. # translations/messages+intl-icu.en.yaml
    2. # the 'other' key is required, and is selected if no other case matches
    3. invitation_title: >-
    4. {organizer_gender, select,
    5. female {{organizer_name} has invited you for her party!}
    6. male {{organizer_name} has invited you for his party!}
    7. other {{organizer_name} have invited you for their party!}
    8. }
  • XML

    1. <!-- translations/messages+intl-icu.en.xlf -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    4. <file source-language="en" datatype="plaintext" original="file.ext">
    5. <body>
    6. <trans-unit id="invitation_title">
    7. <source>invitation_title</source>
    8. <!-- the 'other' key is required, and is selected if no other case matches -->
    9. <target>{organizer_gender, select,
    10. female {{organizer_name} has invited you for her party!}
    11. male {{organizer_name} has invited you for his party!}
    12. other {{organizer_name} have invited you for their party!}
    13. }</target>
    14. </trans-unit>
    15. </body>
    16. </file>
    17. </xliff>
  • PHP

    1. // translations/messages+intl-icu.en.php
    2. return [
    3. // the 'other' key is required, and is selected if no other case matches
    4. 'invitation_title' => '{organizer_gender, select,
    5. female {{organizer_name} has invited you for her party!}
    6. male {{organizer_name} has invited you for his party!}
    7. other {{organizer_name} have invited you for their party!}
    8. }',
    9. ];

This might look very complex. The basic syntax for all functions is {variable_name, function_name, function_statement} (where, as you see later, function_statement is optional for some functions). In this case, the function name is select and its statement contains the “cases” of this select. This function is applied over the organizer_gender variable:

  1. // prints "Ryan has invited you for his party!"
  2. echo $translator->trans('invitation_title', [
  3. 'organizer_name' => 'Ryan',
  4. 'organizer_gender' => 'male',
  5. ]);
  6. // prints "John & Jane have invited you for their party!"
  7. echo $translator->trans('invitation_title', [
  8. 'organizer_name' => 'John & Jane',
  9. 'organizer_gender' => 'not_applicable',
  10. ]);

The {...} syntax alternates between “literal” and “code” mode. This allows you to use literal text in the select statements:

  1. The first {organizer_gender, select, ...} block starts the “code” mode, which means organizer_gender is processed as a variable.
  2. The inner {... has invited you for her party!} block brings you back in “literal” mode, meaning the text is not processed.
  3. Inside this block, {organizer_name} starts “code” mode again, allowing organizer_name to be processed as variable.

Tip

While it might seem more logical to only put her, his or their in the switch statement, it is better to use “complex arguments” at the outermost structure of the message. The strings are in this way better readable for translators and, as you can see in the other case, other parts of the sentence might be influenced by the variables.

Pluralization

Another interesting function is plural. It allows you to handle pluralization in your messages (e.g. There are 3 apples vs There is one apple). The function looks very similar to the select function:

  • YAML

    1. # translations/messages+intl-icu.en.yaml
    2. num_of_apples: >-
    3. {apples, plural,
    4. =0 {There are no apples}
    5. one {There is one apple...}
    6. other {There are # apples!}
    7. }
  • XML

    1. <!-- translations/messages+intl-icu.en.xlf -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    4. <file source-language="en" datatype="plaintext" original="file.ext">
    5. <body>
    6. <trans-unit id="num_of_apples">
    7. <source>num_of_apples</source>
    8. <target>{apples, plural, =0 {There are no apples} one {There is one apple...} other {There are # apples!}}</target>
    9. </trans-unit>
    10. </body>
    11. </file>
    12. </xliff>
  • PHP

    1. // translations/messages+intl-icu.en.php
    2. return [
    3. 'num_of_apples' => '{apples, plural,
    4. =0 {There are no apples}
    5. one {There is one apple...}
    6. other {There are # apples!}
    7. }',
    8. ];

Pluralization rules are actually quite complex and differ for each language. For instance, Russian uses different plural forms for numbers ending with 1; numbers ending with 2, 3 or 4; numbers ending with 5, 6, 7, 8 or 9; and even some exceptions of this!

In order to properly translate this, the possible cases in the plural function are also different for each language. For instance, Russian has one, few, many and other, while English has only one and other. The full list of possible cases can be found in Unicode’s Language Plural Rules document. By prefixing with =, you can match exact values (like 0 in the above example).

Usage of this string is the same as with variables and select:

  1. // prints "There is one apple..."
  2. echo $translator->trans('num_of_apples', ['apples' => 1]);
  3. // prints "There are 23 apples!"
  4. echo $translator->trans('num_of_apples', ['apples' => 23]);

Note

You can also set an offset variable to determine whether the pluralization should be offset (e.g. in sentences like You and # other people / You and # other person).

Tip

When combining the select and plural functions, try to still have select as outermost function:

  1. {gender_of_host, select,
  2. female {{num_guests, plural, offset:1
  3. =0 {{host} does not give a party.}
  4. =1 {{host} invites {guest} to her party.}
  5. =2 {{host} invites {guest} and one other person to her party.}
  6. other {{host} invites {guest} and # other people to her party.}
  7. }}
  8. male {{num_guests, plural, offset:1
  9. =0 {{host} does not give a party.}
  10. =1 {{host} invites {guest} to his party.}
  11. =2 {{host} invites {guest} and one other person to his party.}
  12. other {{host} invites {guest} and # other people to his party.}
  13. }}
  14. other {{num_guests, plural, offset:1
  15. =0 {{host} does not give a party.}
  16. =1 {{host} invites {guest} to their party.}
  17. =2 {{host} invites {guest} and one other person to their party.}
  18. other {{host} invites {guest} and # other people to their party.}
  19. }}
  20. }

Using Ranges in Messages

The pluralization in the legacy Symfony syntax could be used with custom ranges (e.g. have a different messages for 0-12, 12-40 and 40+). The ICU message format does not have this feature. Instead, this logic should be moved to PHP code:

  1. // Instead of
  2. $message = $translator->trans('balance_message', $balance);
  3. // with a message like:
  4. // ]-Inf,0]Oops! I'm down|]0,1000]I still have money|]1000,Inf]I have lots of money
  5. // use three different messages for each range:
  6. if ($balance < 0) {
  7. $message = $translator->trans('no_money_message');
  8. } elseif ($balance < 1000) {
  9. $message = $translator->trans('some_money_message');
  10. } else {
  11. $message = $translator->trans('lots_of_money_message');
  12. }

Additional Placeholder Functions

Besides these, the ICU MessageFormat comes with a couple other interesting functions.

Ordinal

Similar to plural, selectordinal allows you to use numbers as ordinal scale:

  • YAML

    1. # translations/messages+intl-icu.en.yaml
    2. finish_place: >-
    3. You finished {place, selectordinal,
    4. one {#st}
    5. two {#nd}
    6. few {#rd}
    7. other {#th}
    8. }!
    9. # when only formatting the number as ordinal (like above), you can also
    10. # use the `ordinal` function:
    11. finish_place: You finished {place, ordinal}!
  • XML

    1. <!-- translations/messages+intl-icu.en.xlf -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    4. <file source-language="en" datatype="plaintext" original="file.ext">
    5. <body>
    6. <trans-unit id="finish_place">
    7. <source>finish_place</source>
    8. <target>You finished {place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}!</target>
    9. </trans-unit>
    10. <!-- when only formatting the number as ordinal (like
    11. above), you can also use the `ordinal` function: -->
    12. <trans-unit id="finish_place">
    13. <source>finish_place</source>
    14. <target>You finished {place, ordinal}!</target>
    15. </trans-unit>
    16. </body>
    17. </file>
    18. </xliff>
  • PHP

    1. // translations/messages+intl-icu.en.php
    2. return [
    3. 'finish_place' => 'You finished {place, selectordinal,
    4. one {#st}
    5. two {#nd}
    6. few {#rd}
    7. other {#th}
    8. }!',
    9. // when only formatting the number as ordinal (like above), you can
    10. // also use the `ordinal` function:
    11. 'finish_place' => 'You finished {place, ordinal}!',
    12. ];
  1. // prints "You finished 1st!"
  2. echo $translator->trans('finish_place', ['place' => 1]);
  3. // prints "You finished 9th!"
  4. echo $translator->trans('finish_place', ['place' => 9]);
  5. // prints "You finished 23rd!"
  6. echo $translator->trans('finish_place', ['place' => 23]);

The possible cases for this are also shown in Unicode’s Language Plural Rules document.

Date and Time

The date and time function allows you to format dates in the target locale using the [IntlDateFormatter](https://www.php.net/manual/en/class.intldateformatter.php "IntlDateFormatter"):

  • YAML

    1. # translations/messages+intl-icu.en.yaml
    2. published_at: 'Published at {publication_date, date} - {publication_date, time, short}'
  • XML

    1. <!-- translations/messages+intl-icu.en.xlf -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    4. <file source-language="en" datatype="plaintext" original="file.ext">
    5. <body>
    6. <trans-unit id="published_at">
    7. <source>published_at</source>
    8. <target>Published at {publication_date, date} - {publication_date, time, short}</target>
    9. </trans-unit>
    10. </body>
    11. </file>
    12. </xliff>
  • PHP

    1. // translations/messages+intl-icu.en.php
    2. return [
    3. 'published_at' => 'Published at {publication_date, date} - {publication_date, time, short}',
    4. ];

The “function statement” for the time and date functions can be one of short, medium, long or full, which correspond to the constants defined by the IntlDateFormatter class:

  1. // prints "Published at Jan 25, 2019 - 11:30 AM"
  2. echo $translator->trans('published_at', ['publication_date' => new \DateTime('2019-01-25 11:30:00')]);

Numbers

The number formatter allows you to format numbers using Intl’s [NumberFormatter](https://www.php.net/manual/en/class.numberformatter.php "NumberFormatter"):

  • YAML

    1. # translations/messages+intl-icu.en.yaml
    2. progress: '{progress, number, percent} of the work is done'
    3. value_of_object: 'This artifact is worth {value, number, currency}'
  • XML

    1. <!-- translations/messages+intl-icu.en.xlf -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    4. <file source-language="en" datatype="plaintext" original="file.ext">
    5. <body>
    6. <trans-unit id="progress">
    7. <source>progress</source>
    8. <target>{progress, number, percent} of the work is done</target>
    9. </trans-unit>
    10. <trans-unit id="value_of_object">
    11. <source>value_of_object</source>
    12. <target>This artifact is worth {value, number, currency}</target>
    13. </trans-unit>
    14. </body>
    15. </file>
    16. </xliff>
  • PHP

    1. // translations/messages+intl-icu.en.php
    2. return [
    3. 'progress' => '{progress, number, percent} of the work is done',
    4. 'value_of_object' => 'This artifact is worth {value, number, currency}',
    5. ];
  1. // prints "82% of the work is done"
  2. echo $translator->trans('progress', ['progress' => 0.82]);
  3. // prints "100% of the work is done"
  4. echo $translator->trans('progress', ['progress' => 1]);
  5. // prints "This artifact is worth $9,988,776.65"
  6. // if we would translate this to i.e. French, the value would be shown as
  7. // "9 988 776,65 €"
  8. echo $translator->trans('value_of_object', ['value' => 9988776.65]);

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.