Ternary in Laravel Blade

后端 未结 5 1183
刺人心
刺人心 2020-12-23 11:02

Looking for a ternary operator for blade templates

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

Can\'t seem to get it to work this works

         


        
相关标签:
5条回答
  • 2020-12-23 11:42

    This works:

    {{ Auth::check() ? 'yes' : 'no' }}
    
    0 讨论(0)
  • 2020-12-23 11:44

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

    {{ Auth::check() ? 'yes' : 'no' }}
    
    0 讨论(0)
  • 2020-12-23 11:45

    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' }}
    
    0 讨论(0)
  • 2020-12-23 12:01

    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”.

    0 讨论(0)
  • 2020-12-23 12:05

    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

    0 讨论(0)
提交回复
热议问题