-1

Are there any ways for pluralizing a string in Symfony 3? For example: I have "Object" and I would like to get "Objects".

lordrhodos
  • 2,689
  • 1
  • 24
  • 37

1 Answers1

0

pluralization is a very complex topic and Symfony embraces it as part if the Translation Component:

Message pluralization is a tough topic as the rules can be quite complex.

So you basically would need to activate translations for your system and translate the needed strings using the transChoice() method of the translator service or the 'transchoice' tag / filter in your twig template.

To handle this, use the transChoice() method or the transchoice tag/filter in your template.

using the translator service

// the %count% placeholder is assigned to the second argument...
$translator->transChoice(
    'There is one apple|There are %count% apples',
    10
);


// ...but you can define more placeholders if needed
$translator->transChoice(
    'Hurry up %name%! There is one apple left.|There are %count% apples left.',
    10,
    // no need to include %count% here; Symfony does that for you
    array('%name%' => $user->getName())
);

twig tags

{% trans %}Hello %name%{% endtrans %}

{% transchoice count %}
    {0} There are no apples|{1} There is one apple|]1,Inf[ There are %count% apples
{% endtranschoice %}

UPDATE

If you do not know the string beforehand you can use the internal Inflector Component, but be aware of the disclaimer and the fact that this would only work for strings in English:

This component is currently marked as internal. Do not use it in your own code. Breaking changes may be introduced in the next minor version of Symfony, or the component itself might even be removed completely.

An alternative would be to create your own inflector class, e.g. something like this and create a service from it.

lordrhodos
  • 2,689
  • 1
  • 24
  • 37
  • I don't know the string beforehand, so I can't use that. – Antonio González Borrego Jul 04 '17 at 20:30
  • you can try the [inflector component](https://github.com/symfony/inflector), although it is marked for internal usage only ;-) – lordrhodos Jul 05 '17 at 05:55
  • I found that solution last night. Inflector component is marked for internal usage only as you said. However there are some popular bundles like FOSRestBundle which are using it. I also saw Doctrine's Inflector. This one seems a little advanced for me. Thank you for your answer. – Antonio González Borrego Jul 05 '17 at 13:42