October CMS resources and help articles

Simple and to the point. Optimized by the community.

Using Pluralization with String Translations

1
by mjauvin, last modified on February 3rd, 2020

Laravel's trans_choice() provides the means to correctly pluralize strings in different locales with very flexible rules.

First, create your translation strings:

/plugins/author/plugin/lang/en/lang.php:

<?php return [
   'choice' => '{0} There are no apples|{1} There is one apple|[2,Inf] There are :count apples',
];
/plugins/author/plugin/lang/fr/lang.php

<?php return [
   'choice' => "{0} Il n'y a pas de pomme|{1} Il y a une pomme|[2,Inf] Il y a :count pommes",
];

Use it in twig with the transchoice filter:

Example in twig:

{{ 'author.plugin::lang.choice' | transchoice(0) }}
{{ 'author.plugin::lang.choice' | transchoice(1) }}
{{ 'author.plugin::lang.choice' | transchoice(10) }}

Use it in PHP code with the trans_choice() function:

Example in PHP code:

$zero = trans_choice('author.plugin::lang.choice', 0);
$one = trans_choice('author.plugin::lang.choice', 1);
$ten = trans_choice('author.plugin::lang.choice', 10);

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?