Created
October 31, 2017 13:11
-
-
Save daviddarnes/5e142eff7a77270c5f93d456e040a9bf to your computer and use it in GitHub Desktop.
Pluralising with Twig
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% spaceless %} | |
{% if integer > 1 %} | |
{{ plural }} | |
{% else %} | |
{{ singular }} | |
{% endif %} | |
{% endspaceless %} |
Or try this:
{{ post.bed_count }} {{ _n( 'bedroom', 'bedrooms', post.bed_count ) }}
@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
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
Usage: