How to translate with pluralization in Twig? How to translate with pluralization in Twig? symfony symfony

How to translate with pluralization in Twig?


I would use a solution like this:

messages.en.xliff:

<trans-unit id="1">    <source>some.translation.key</source>    <target>{0} no.attendee|{1} one attendee|{2} two attendees|{3} three attendees|]3,Inf] many attendees</target></trans-unit>

Twig template:

{{ 'some.translation.key'|transchoice(count) }}

If you need to put some arguments, you should pass them as second argument.

Here's the prototype of the filter:

public function transchoice($message, $count, array $arguments = array(), $domain = "messages", $locale = null)


Found this from Symfony Documentation:

Symfony2 provides specialized Twig tags (trans and transchoice) to help with message translation of static blocks of text:

{% trans %}Hello %name%{% endtrans %}{% transchoice count %}{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples{% endtranschoice %}

The transchoice tag automatically gets the %count% variable from the current context and passes it to the translator. This mechanism only works when you use a placeholder following the %var% pattern.


This subject is quite old, but I would suggest you to do something like that :

In your messages.LOCALE.yml

you.translaction.key: "{1}1 Comment|]1,Inf]%count% Comments"

In your twig template

{% set count = 2 %}{% transchoice count with {'%count%': count} %}you.translaction.key{% endtranschoice %}

Cheers,

Simon