Laravel - 检查@yield是否为空

2022-08-30 09:18:24

是否可以签入边栏选项卡视图(如果@yield是否有内容?

我正在尝试在视图中分配页面标题:

@section("title", "hi world")

所以我想检查一下主布局视图...像这样:

<title> Sitename.com {{ @yield('title') ? ' - '.@yield('title') : '' }} </title>

答案 1

对于那些现在(2018 +)的人来说,您可以使用:

@hasSection('name')
   @yield('name')
@endif

请参见: https://laravel.com/docs/5.6/blade#control-structures


答案 2

在Laravel 5中,我们现在有一个可以在立面上调用的方法。hasSectionView

您可以使用 来检查是否为空:View::hasSection@yeild

<title>
    @if(View::hasSection('title'))
        @yield('title')
    @else
        Static Website Title Here
    @endif
</title>

此条件是检查在我们的视图中是否设置了具有标题名称的部分。

 

提示:我看到很多新工匠将标题部分设置为如下所示:

@section('title')
Your Title Here
@stop

但是您可以通过将默认值作为第二个参数传递来简化此操作:

@section('title', 'Your Title Here')

 

该方法已于 2015 年 4 月 15 日添加。hasSection


推荐