Skip to content

Instantly share code, notes, and snippets.

@daviddarnes
Created October 31, 2017 13:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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 %}
@daviddarnes
Copy link
Author

Usage:

{% include 'pluralise.twig' with {
  integer: post.bed_count,
  plural: 'bedrooms',
  singular: 'bedroom'
} %}

@daviddarnes
Copy link
Author

daviddarnes commented Oct 31, 2017

Or try this:

{{ post.bed_count }} {{ _n( 'bedroom', 'bedrooms', post.bed_count ) }}

@daviddarnes
Copy link
Author

@Machou whatever application you're working in probably doesn't have this function included. For example WordPress comes with this function available and therefore available in Twig

@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