Skip to content

Instantly share code, notes, and snippets.

@tasiot
Last active January 5, 2024 16:56
Show Gist options
  • Save tasiot/b85aa195c622f4c15c095a2cae8ccfc2 to your computer and use it in GitHub Desktop.
Save tasiot/b85aa195c622f4c15c095a2cae8ccfc2 to your computer and use it in GitHub Desktop.
Twig pluralize filter

Usage

Two parameters, singular and plural text

Value: 0, show "You have 0 apple."

{% set apples = 0 %} {{ apples|pluralize('You have {} apple.', 'You have {} apples.') }}

Value: 1, show "You have 1 apple."

{% set apples = 0 %} {{ apples|pluralize('You have {} apple.', 'You have {} apples.') }}

Value: 2, show "You have 2 apples."

{% set apples = 0 %} {{ apples|pluralize('You have {} apple.', 'You have {} apples.') }}

Three parameters, singular, plural and zero text

Value: 0, show "You don't have an apple."

{% set apples = 0 %} {{ apples|pluralize('You have only one apple.', 'You have {} apples.', 'You don\'t have an apple.') }}

Value: 1, show "You have only one apple."

{% set apples = 0 %} {{ apples|pluralize('You have only one apple.', 'You have {} apples.', 'You don\'t have an apple.') }}

Value: 2, show "You have 2 apples."

{% set apples = 0 %} {{ apples|pluralize('You have only one apple.', 'You have {} apples.', 'You don\'t have an apple.') }}

<?php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class AppExtension extends AbstractExtension
{
public function getFilters(): array
{
return [
new TwigFilter('pluralize', [$this, 'pluralize'])
];
}
public function pluralize(int $count, string $singular, string $plural, string $zero = null): string
{
if ($count > 1){
return str_replace('{}', $count, $plural);
} else if ($count <= 0 && null !== $zero){
return $zero; // No string replacement required for zero
}
return str_replace('{}', $count, $singular);
}
}
@tasiot
Copy link
Author

tasiot commented Dec 2, 2022

Ok. In French the plural is only if the value is > 1 (and I'm french ^^).

  • 0 pomme
  • 1 pomme
  • 2 pommes
  • 3 pommes

You can adjust it easily if you need to change the rule.

@brettsantore
Copy link

Thank you for the work you did. It's pretty much what I'm looking for. Merci!

@tasiot
Copy link
Author

tasiot commented Dec 2, 2022

You are welcome! Thank you for your message

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment