【问题标题】:Echoing Data After Checking For Existence - In A Form检查存在后回显数据 - 以表格形式
【发布时间】:2014-09-29 13:24:50
【问题描述】:

我正在尝试使用“或”方式检查刀片模板中的数据。

我愿意:

{{{ $data['news']->title or 'Default' }}}

上面给出了我的数据,如果它存在或默认,如果它不存在。

我遇到的问题是在表单字段默认值中使用它时:

{{ Form::text('username', $data['news']->title or 'Default') }}

它失败了,如果数据确实存在,它输出1,如果不存在未定义索引的页面错误:news。

【问题讨论】:

    标签: laravel laravel-4 blade


    【解决方案1】:

    or 加糖语法仅在 echoing 直接使用时有效,而不是在将其传递给 php 函数时。


    如果你确定它有一个title 属性,但它可能是空的,你可以不用这样:

    {{ Form::text('username', $data['news']->title ?: 'Default') }}
    

    如果您不确定title 属性或news 键,但$data 变量肯定存在,您可以使用:

    {{ Form::text('username', data_get($data, 'news.title', 'Default')) }}
    

    如果 $data 变量本身可能丢失,您将不得不求助于:

    {{ Form::text('username', empty($data['news']->title) ? 'Default' : $data['news']->title) }}
    

    【讨论】:

    • 谢谢,有没有更好的操作符只输出$data,如果它存在,如果它不存在,什么都不输出?
    • @panthro 正是我向您展示的代码,但将 'Default' 替换为 ''
    • 如果您有强迫症并希望保持默认参数值与框架相同,请使用 null
    猜你喜欢
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 2012-05-02
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多