神刀安全网

str_plural(): Quickest way to show plural noun – Laravel Daily

Laravel has a lot of helpers, for example to work with strings or arrays. One of them in particular helps with pluralization. Here’s what I mean.

Imagine a situation where you have to show text “X item(s)”, where if X > 1 then it’s “items”, otherwise “1 item”. How do we do that in Blade with simple IF?

{{ $items }} @if ($items > 1) items @else item @endif 

Or a little shorter:

{{ $items }} item{{ ($items > 1) ? 's' : '' }} 

But there’s even shorter way – with function str_plural() :

{{ $items }} {{ str_plural('item', $items) }} 

Function str_plural($noun, $count) has two parameters – it checks second parameter $count , and if its value is greater than 1 – it pluralizes the first parameter $noun .

Actually, second parameter is optional – so if you just want to show pluralize form of a noun, you can just do something like this:

{{ str_plural('child') }} 

It would show ‘children’.

Any more useful helpers that are your favorites in Laravel? Let me know in the comments.

Facebook
Twitter
Google+
LinkedIn

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » str_plural(): Quickest way to show plural noun – Laravel Daily

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮