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 :)

推荐答案

Use php's null coalesce operator:

{{ $variable ?? "Default Message" }}

Removed as of Laravel 5.7

使用Laravel 4.1-5.6,您可以简单地这样做:

{{ $variable or "Default Message" }}

这和:

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

Laravel相关问答推荐

有没有办法使用laravel EXCEL读取和修改EXCEL文件?

CKEditor在laravel中的p标记之前和之后添加额外的p标记

如何在Vite和Rollup中完全禁用分块?

如何在 vue 模板中引用 laravel csrf 字段

Laravel中具有两个外键字段的数据库一对多

Laravel 5 - 仅在特定页面/控制器(页面特定assets资源)上添加样式表

路由中间的可选参数

Laravel Electron邮件验证模板位置

Laravel 干预图像 GD 库扩展

将非框架 PHP 项目移植到 Laravel 4.x

Laravel 将参数从路由传递到过滤器

Auth 在 Laravel Tinker 中不起作用

如何处理 php (Laravel api) 和 javascript (AngularJS) 之间的日期时间

Laravel 字符串验证以允许空字符串

如何在 Laravel 视图中找到当前语言?

Grammar::parameterize() 必须是数组类型

如何在 laravel 用户删除中重置自动增量?

Laravel 部署……有标准的方式吗?

Laravel 更新后用户模型错误(用户类包含 3 个抽象方法)

为什么`catch (Exception $e)` 不处理这个`ErrorException`?