如果在 blade 模板中设置了变量,如何避免每次都检查? Laravel 8
How to avoid checking every time, if variable is set in blade template? Laravel 8
我知道这样的事情:
{{ old('contents', $page->contents ?? null) }}
但是更复杂的情况呢,比如复选框和 selects?
<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 输入中做到这一点?
我不确定我是否完全理解您要尝试做的事情,但这种方法可能会有所帮助;如果您使用 JQuery:
<script>
$(document).ready(function() {
@if($page->custom_template)
$('option[value="{{ $page->custom_template}}"]').prop("selected", true);
@endif
});
</script>
您可以使用类型提示来避免 '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'));
}
在创建函数中使用 'Type hinting' 将创建页面实体的空集合。无需检查视图中的 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>
通过使用上述条件,您可以使用相同的视图来创建和编辑功能。
希望这能解决您的问题。
我知道这样的事情:
{{ old('contents', $page->contents ?? null) }}
但是更复杂的情况呢,比如复选框和 selects?
<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 输入中做到这一点?
我不确定我是否完全理解您要尝试做的事情,但这种方法可能会有所帮助;如果您使用 JQuery:
<script>
$(document).ready(function() {
@if($page->custom_template)
$('option[value="{{ $page->custom_template}}"]').prop("selected", true);
@endif
});
</script>
您可以使用类型提示来避免 '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'));
}
在创建函数中使用 'Type hinting' 将创建页面实体的空集合。无需检查视图中的 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>
通过使用上述条件,您可以使用相同的视图来创建和编辑功能。
希望这能解决您的问题。