在刀片中快速 IF 语句的优雅方式

Mic*_*ael 0 php if-statement web laravel blade

我是 Laravel 的新手,我知道我可以像这样在双大括号内回显变量:

<p>{{ $posts->id }}</p>
Run Code Online (Sandbox Code Playgroud)

现在,在我的情况下,我有一个表单,有时包含要更新的变量 $posts(顺便说一下,这是表),有时不包含它以根据 URL 中的参数插入一行。

当然,如果没有帖子,则“-> id”部分将失败。有没有一种优雅的方法可以在这里快速创建 IF 语句,例如:

<?php if ($posts) echo $posts["id"]; ?>
Run Code Online (Sandbox Code Playgroud)

但只是使用刀片引擎。

我知道我可以在 HTML 块周围使用 @if ,但是我必须一直编写该块两次。

Ale*_*nin 5

这取决于究竟是什么$posts

您可以使用三元语句。例如,如果$posts是集合或数组,请使用empty

{{ empty($posts) ? '' : $posts->id }}
Run Code Online (Sandbox Code Playgroud)

如果它只是变量,请使用 isset()

在某些情况下可以使用or语法:

{{ $posts or 'It is empty' }}
Run Code Online (Sandbox Code Playgroud)

在 PHP7 中,您可以使用??(null 合并运算符) 来检查变量isset(). 例如:

{{ $posts ?? $posts->id }}
Run Code Online (Sandbox Code Playgroud)

你可以在官方文档中看到另一个解释(见Echoing Data If It Exists部分)。