How to echo a default value if value not set blade

2019-03-09 00:20发布

问题:

I would like to know what would be the best way to display a default value if the given value is not set. I have the following in a blade file (I can not guaranty that the key is set, it depends on a multitude of factors).

{{ $foo['bar'] }}

I would know if the following is the best way to go about it,

{{ (isset($foo['bar']) ? $foo['bar'] : 'baz' }}

or is there a better way to do this?

Thanks :)

回答1:

With Laravel 4.1+ you can simply do it like this:

{{ $Variable or "Default Message" }}

It's the exact same as:

echo isset($Variable) ? $Variable : 'Default Message'; 

Edit: On a side note, above is supported in PHP 7+, using ??

echo $Variable ?? 'Default Message';


回答2:

PHP 5.3's ternary shortcut syntax works in Blade templates:

{{ $foo->bar ?: 'baz' }}

It won't work with undefined top-level variables, but it's great for handling missing values in arrays and objects.



回答3:

Since Laravel 5.7 {{$Variable or "Default Message"}} throws $Variable is not defined. This {{$Variable ?? "Default Message"}} works though.



回答4:

I recommend setting the default value in your controller instead of making a work-around in your view.

This is the best way because it keeps logic out of your view, and keeps the view's markup clean.

For example in your controller, before passing data to the view:

if(!isset($foo['bar'])){
     $foo['bar'] = 'baz';
}


回答5:

While Chris B's answer is perfectly valid; I felt perhaps this is a question that can have an alternative answer. Some would prefer not to make their controllers "fat" and in this case at least, the use of a Presenter could be the answer you seek for allowing a great deal of flexibility in your application views.

Take a look at the following project/package on Github. The readme is pretty robust with a number of examples to get you going.

It will allow you to do just what you asked and simply call

{{ $foo['bar'] }}

in your view.