【问题标题】:Elegant way for quick IF statement in blade在刀片中快速 IF 语句的优雅方式
【发布时间】:2017-05-10 12:17:19
【问题描述】:

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

<p>{{ $posts->id }}</p>

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

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

<?php if ($posts) echo $posts["id"]; ?>

但只是使用刀片引擎。

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

【问题讨论】:

    标签: php laravel if-statement web blade


    【解决方案1】:

    这取决于$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 部分)。

    【讨论】:

    • $posts 是 Post::findOrFail 的结果,我相信它只是 JSON,Post 是我代表数据库表的模型。
    • findOrFail() 如果未找到帖子,则返回异常。请改用find() 或where()-&gt;first(),这将返回null。在这种情况下,您将能够使用三元运算符{{ is_null($post) ? '' : $post-&gt;id }}
    • findOrFail() 不会返回 json;它将返回一个对象(或失败时抛出异常)
    【解决方案2】:

    另一种更“类似laravel”的方式是optional helper。

    {{ optional($posts)->id }}
    

    与old helper 配合使用非常好。

    【讨论】:

      猜你喜欢
      • 2022-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      • 2022-06-17
      相关资源
      最近更新 更多