Laravel - Check if @yield empty or not

后端 未结 17 1915
醉梦人生
醉梦人生 2021-01-31 02:08

Is it possible to check into a blade view if @yield have content or not?

I am trying to assign the page titles in the views:

@section(\"title\", \"hi wor         


        
相关标签:
17条回答
  • 2021-01-31 02:33

    New in Laravel 7.x -- sectionMissing():

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

    Check if section is missing:

    @sectionMissing('name')
       @yield('alternative')
    @endif
    
    0 讨论(0)
  • 2021-01-31 02:34

    Sometimes you have an enclosing code, which you only want to have included in that section is not empty. For this problem I just found this solution:

    @if (filled(View::yieldContent('sub-title')))
        <h2>@yield('sub-title')</h2>
    @endif
    

    The title H2 gets only displayed it the section really contains any value. Otherwise it won't be printed...

    0 讨论(0)
  • 2021-01-31 02:38

    I have a similar problem with the solution:

    @section('bar', '')
    @hasSection('bar')
    <div>@yield('bar')</div>
    @endif
    //Output
    <div></div>
    

    The result will be the empty <div></div>

    Now, my suggestion, to fix this, is

    @if (View::hasSection('bar') && !empty(View::yieldContent('bar')))
    <div>@yield('bar')</div>
    @endif
    
    0 讨论(0)
  • 2021-01-31 02:44

    Can you not do:

    layout.blade.php

    <title> Sitename.com @section("title") Default @show </title>

    And in subtemplate.blade.php:

    @extends("layout")
    
    @section("title") My new title @stop
    
    0 讨论(0)
  • 2021-01-31 02:45

    I don't think you can, but you have options, like using a view composer to always provide a $title to your views:

    View::composer('*', function($view)
    {
        $title = Config::get('app.title');
    
        $view->with('title', $title ? " - $title" : '');
    });
    
    0 讨论(0)
提交回复
热议问题