Laravel - Difference between @yield and @section?

dayuloli picture dayuloli · Mar 16, 2015 · Viewed 51k times · Source

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

<html>
    <body>
        @section('sidebar')
            This is the master sidebar.
        @show

        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

Since @yield can also pass in some default content using @yield('section', 'Default Content'), is @yield just a shorthand for a @section that do not uses @parent?

@section
    <!-- Nothing here -->
@show

What other differences are there?

Answer

Adam picture Adam · Oct 1, 2017

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

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Test</title>
  </head>
  <body>
    <h1>This is a test</h1>

    @yield('mainA')
    @yield('mainB', 'This is the alternative 1')
    @yield('mainC', '<p>This is the alternative 2</p>')
    @yield('mainD', 'This is the alternative 3')

    @section('testA')
    @show

    @section('testB')
      This is the alternative 4
    @show

    @section('testC')
      <p>This is the alternative 5</p>
    @show

    @section('testD')
      <p>This is the alternative 6</p>
    @show


  </body>
</html>

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

@extends('test')

@section('mainD')
  <div>
    <p>First replacement!</p>
    <hr>
  </div>
@endsection

@section('testC')
  <div>
    <p>Second replacement!</p>
    <hr>
  </div>
@endsection

@section('testD')
  @parent
  <div>
    <p>Additional content</p>
    <hr>
  </div>
@endsection

And that is the outcome:

enter image description here