Creating layout pages

One of the primary benefits of using Blade are template inheritanceopen in new window. It allows a developer to create layout files that will hold common layout elements and extend them to other view templates.

Defining a Layout

The first step to using template inheritance to define a layout. The "master" layout will likely contain typical HTML mark-up, but will also include two Blade directives @section and @yield. The @section directive defines a section of content, while the @yield directive is used to display the contents of a given section. The @show directive is used to end a defined section and immediately yield or display the section.

<!-- Stored in resources/views/layouts/app.blade.php -->

<html>
    <head>
        <title>App Name - @yield('title')</title>
    </head>
    <body>
        @section('sidebar')
            This is the master sidebar.
        @show

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

Extending a Layout

When extending a "master" layout, the child view will use the @extends directive to specify which layout the it should "inherit". Views which extend a Blade layout may inject content into the layout's sections using @section directives. Remember, as seen in the example above, the contents of these sections will be displayed in the layout using @yield:

<!-- Stored in resources/views/child.blade.php -->

@extends('layouts.app')

@section('title', 'Page Title')

@section('sidebar')
    @parent

    <p>This is appended to the master sidebar.</p>
@endsection

@section('content')
    <p>This is my body content.</p>
@endsection

In this example, the sidebar section is utilizing the @parent directive to append (rather than overwriting) content to the layout's sidebar. The @parent directive will be replaced by the content of the layout when the view is rendered. In the above example, @endsection is used instead of @show. Using @endsection means that the section will be defined, but not yielded.