Ternary in Laravel Blade

2019-03-08 12:54发布

Looking for a ternary operator for blade templates

@if(Auth::check()) ? yes : no @endif

Can't seem to get it to work this works

@if(Auth::check()) yes @else no @endif

suppose there is not much in it for this example, just curious.

5条回答
Ridiculous、
2楼-- · 2019-03-08 13:32

in addition, here is a nice shortcut ?:, if you you need to print some variable's value or if it's empty some default text

{{ $value ?: 'Default Value' }}
查看更多
smile是对你的礼貌
3楼-- · 2019-03-08 13:42

For Laravel 5 + php7, you should be using the null coalesce operator as explained in this Laravel News article, like so:

{{ $value ?? "Fallback" }}

Before the null coalescing operator, Blade handled the same problem with the “or” operator, which allows a default value when the first value isn’t set, separated by an “or”.

查看更多
贪生不怕死
4楼-- · 2019-03-08 13:43

You are free to use it with {{ }}.

{{ Auth::check() ? 'yes' : 'no' }}
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-03-08 13:49

I know this question was asked a while ago, but this may help somebody.

You can now do this in Laravel 5.

{{ $variable or "default" }}

Laravel 5 Blade Templates

Laravel 5.2 Blade Template

查看更多
Explosion°爆炸
6楼-- · 2019-03-08 13:57

This works:

{{ Auth::check() ? 'yes' : 'no' }}
查看更多
登录 后发表回答