繁体   English   中英

如果刀片模板中设置了变量,如何避免每次检查? Laravel 8

[英]How to avoid checking every time, if variable is set in blade template? Laravel 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)并检查旧输入。 我该如何在 select 输入中做到这一点?

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

你的 controller

/**
 * 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'));
}

在创建 function 中使用“类型提示”将创建页面实体的空集合。 无需在视图中检查 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>

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

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

我不确定我是否完全理解您要执行的操作,但这种方法可能会有所帮助; 如果您使用的是 JQuery:

<script>
    $(document).ready(function() {
        @if($page->custom_template)
        $('option[value="{{ $page->custom_template}}"]').prop("selected", true);
        @endif
    });
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM