首页 > 解决方案 > 如果刀片模板中设置了变量,如何避免每次检查?拉拉维尔 8

问题描述

我知道这样的事情:

{{ old('contents', $page->contents ?? null) }}

但是更复杂的情况呢,比如复选框和选择?

<select id="custom_template" name="custom_template">
    {{--default empty option, if nothing is selected yet--}}
    <option label=" " {{ ($page->custom_template == null)? "selected" : "" }}></option>

    @foreach($templates as $template)
        <option value="{{ $template->id }}" {{ ($page->custom_template == $template->id)? "selected" : "" }}>{{ $template->name }}</option>
    @endforeach
</select>

我需要避免检查@isset($page)并检查旧输入。我怎样才能在那个选择输入中做到这一点?

标签: laravellaravel-bladelaravel-8

解决方案


您可以使用类型提示来避免“isset”。

你的控制器

/**
 * Show the form for creating a new resource.
 *
 * @param  \App\Entities\Page  $page
 *
 * @return \Illuminate\View\View
 */
public function create(\App\Entities\Page $page)
{
    return view('page', compact('page'));
}

在创建函数中使用“类型提示”将创建页面实体的空集合。无需在视图中检查 isset 条件,$page->custom_template现在会给你 null,而不是错误。

和你的观点,检查旧的输入。

<select id="custom_template" name="custom_template">
    <option value="">Select Option</option>
    
    @foreach($templates as $template)
        <option value="{{ $template->id }}" {{ (old('custom_template', $page->custom_template) == $template->id) ? 'selected' : '' }}>{{ $template->name }}</option>
    @endforeach
</select>

通过使用上述条件,您可以使用相同的视图来创建和编辑功能。

希望,这将解决您的问题。


推荐阅读