blade 中快速 IF 语句的优雅方式
Elegant way for quick IF statement in blade
我是 Laravel 的新手,我知道我可以像这样在双花括号内回显变量:
<p>{{ $posts->id }}</p>
现在,在我的例子中,我有一个表单,有时包含要更新的变量 $posts(顺便说一句,这是 table),有时不包含它以插入行取决于 URL.
中的参数
当然如果没有post那么“->id”部分就会失败。
有没有一种优雅的方法可以在这里做一个快速的 IF 语句,比如:
<?php if ($posts) echo $posts["id"]; ?>
但仅使用 blade 引擎。
我知道我可以在 HTML-block 周围使用 @if,但那样我就不得不一直写那个块两次。
这取决于 $posts
.
到底是什么
可以使用三元语句。例如,如果 $posts
是集合或数组,则使用 empty
:
{{ empty($posts) ? '' : $posts->id }}
如果只是变量,使用isset()
在某些情况下可以使用or
语法:
{{ $posts or 'It is empty' }}
在 PHP7 中,您可以使用 ??
(空合并运算符)来检查变量 isset()
。例如:
{{ $posts ?? $posts->id }}
您可以在 the official documentation 中看到另一个解释(参见 Echoing Data If It Exists
部分)。
另一种更 "laravel-like" 的方法是 optional 助手。
{{ optional($posts)->id }}
与 old
助手配合使用效果很好。
我是 Laravel 的新手,我知道我可以像这样在双花括号内回显变量:
<p>{{ $posts->id }}</p>
现在,在我的例子中,我有一个表单,有时包含要更新的变量 $posts(顺便说一句,这是 table),有时不包含它以插入行取决于 URL.
中的参数当然如果没有post那么“->id”部分就会失败。 有没有一种优雅的方法可以在这里做一个快速的 IF 语句,比如:
<?php if ($posts) echo $posts["id"]; ?>
但仅使用 blade 引擎。
我知道我可以在 HTML-block 周围使用 @if,但那样我就不得不一直写那个块两次。
这取决于 $posts
.
可以使用三元语句。例如,如果 $posts
是集合或数组,则使用 empty
:
{{ empty($posts) ? '' : $posts->id }}
如果只是变量,使用isset()
在某些情况下可以使用or
语法:
{{ $posts or 'It is empty' }}
在 PHP7 中,您可以使用 ??
(空合并运算符)来检查变量 isset()
。例如:
{{ $posts ?? $posts->id }}
您可以在 the official documentation 中看到另一个解释(参见 Echoing Data If It Exists
部分)。
另一种更 "laravel-like" 的方法是 optional 助手。
{{ optional($posts)->id }}
与 old
助手配合使用效果很好。