Laravel - Check if @yield empty or not

后端 未结 17 1914
醉梦人生
醉梦人生 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:29

    There is probably a prettier way to do this. But this does the trick.

    @if (trim($__env->yieldContent('title')))
        <h1>@yield('title')</h1>
    @endif
    
    0 讨论(0)
  • 2021-01-31 02:29

    You can simply check if the section exists:

    if (isset($__env->getSections()['title'])) {
    
        @yield('title');
    }
    

    And you can even go a step further and pack this little piece of code into a Blade extension: http://laravel.com/docs/templates#extending-blade

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

    In Laravel 5 we now have a hasSection method we can call on a View facade.

    You can use View::hasSection to check if @yeild is empty or not:

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

    This conditional is checking if a section with the name of title was set in our view.

     

    Tip: I see a lot of new artisans set up their title sections like this:

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

    but you can simplify this by just passing in a default value as the second argument:

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

     

    The hasSectionmethod was added April 15, 2015.

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

    For those looking on it now (2018+), you can use :

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

    See : https://laravel.com/docs/5.6/blade#control-structures

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

    Given from the docs:

    @yield('section', 'Default Content');
    

    Type in your main layout e.g. "app.blade.php", "main.blade.php", or "master.blade.php"

    <title>{{ config('app.name') }} - @yield('title', 'Otherwise, DEFAULT here')</title>
    

    And in the specific view page (blade file) type as follows:

    @section('title')
    My custom title for a specific page
    @endsection
    
    0 讨论(0)
  • 2021-01-31 02:33
    @if (View::hasSection('my_section'))
        <!--Do something-->
    @endif
    
    0 讨论(0)
提交回复
热议问题