Outputting the Content of a Blade Section

Problem

You want to output a section in your Blade template.

Solution

Use the Blade @yield command.

Consider the following Blade template.

@section('bottom')
  This is the bottom
@stop
@section('top')
  This is the top
@stop
@yield('top')
@yield('bottom')

The output would be the follwoing.

This is the top
This is the bottom

You can also specify the default value with @yield.

Imagine having the simple layout presented below. (See Using Blade Layouts to Extend Templates.)

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

When a view without a @section('content') extends this layout, the output will be similar to what's below.

<html>
  <body>
    <div class="container">
      No content
    </div>
  </body>
</html>

Discussion

Using default values on @yield is a good way to note when content is missing.

What if you had the line below in your layout?

@yield('content', '<span style="background:red">MISSING CONTENT</span>')

Then whenever the content is not provided it will be very apparent with a big red block saying MISSING CONTENT.

comments powered by Disqus