Laravel - Difference between @yield and @section?

后端 未结 5 1305
鱼传尺愫
鱼传尺愫 2021-01-31 03:33

From the Laravel docs, you can include \'sections\' inside layouts using two methods:


    
        @section(\'sidebar\')
            Thi         


        
5条回答
  •  面向向阳花
    2021-01-31 04:00

    Short Answer: Always use @yield unless you want to do something more complicated then providing a default string.


    Long Answer: Both @yield and @section .. @show are used to be optionally overwritten whenever you extend the blade template. Everything you can do with @yield can also be done with @section .. @show but not the other way around. Here is what they do:

    @yield('main')

    • Can be replaced by @section('main') .. @endsection
    • Can be provided with a default string but no HTML! The default string will be shown in the sub-blade-template when no @section('main') .. @endsection is provided.

    @section('main') .. @show

    • Can be replaced by @section('main') .. @endsection
    • Can be provided with a default HTML code. The default HTML code will be shown in the sub-blade-template when no @section('main') is provided.
    • Can be replaced by @section('main')@parent .. @endsection and additionally shows the default HTML code.

    Here some examples:test.blade.php

    
    
      
        
        Test
      
      
        

    This is a test

    @yield('mainA') @yield('mainB', 'This is the alternative 1') @yield('mainC', '

    This is the alternative 2

    ') @yield('mainD', 'This is the alternative 3') @section('testA') @show @section('testB') This is the alternative 4 @show @section('testC')

    This is the alternative 5

    @show @section('testD')

    This is the alternative 6

    @show

    here is another file called testA.blade.php which extends the other bladed file:

    @extends('test')
    
    @section('mainD')
      

    First replacement!


    @endsection @section('testC')

    Second replacement!


    @endsection @section('testD') @parent

    Additional content


    @endsection

    And that is the outcome:

提交回复
热议问题