Skip to content

Instantly share code, notes, and snippets.

@daviddarnes
Created October 31, 2017 13:11
Show Gist options
  • Save daviddarnes/5e142eff7a77270c5f93d456e040a9bf to your computer and use it in GitHub Desktop.
Save daviddarnes/5e142eff7a77270c5f93d456e040a9bf to your computer and use it in GitHub Desktop.
Pluralising with Twig
{% spaceless %}
{% if integer > 1 %}
{{ plural }}
{% else %}
{{ singular }}
{% endif %}
{% endspaceless %}
@tasiot
Copy link

tasiot commented May 25, 2021

Hello, here is my implementation via a twig filter, a bit inspired by AngularJS's ngPluralize filter.

{{nbMessages | pluralize ('{} message', '{} messages')}} // 0 message, 1 message, 2 messages
{{nbMessages | pluralize ('{} message', '{} messages', 'no message')}} // no message, 1 message, 2 messages
<?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);
  }
}

My gist: https://gist.github.com/tasiot/b85aa195c622f4c15c095a2cae8ccfc2

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