Blade Layouts

Most web applications maintain the same general layout across various pages. However, web applications would be cumbersome and hard to maintain if the entire layout is repeated for every view. Fortunate, Blade supports two convenient ways of building layoutsopen in new window.

Components

Blade Componentsopen in new window can be used to create a layout for a web application. Start by defining the layout component and storing it inside the /resources/views/components/ directory.

NOTE

The layout component must be stored in /resources/views/components/. Unfortunately, this directory does not exist in the default Laravel install and will need to be created manually.

The layout component will contain the general layout for the web application. In addition, a slot will be added where the custom content will be added to the layout.

<!-- resources/views/components/layout.blade.php -->
<html>
    <head>
        <title>{{ $title ?? 'Default Title' }}</title>
        <link rel="stylesheet" href="/app.css">
    </head>
    <body>
        {{ $slot }}
    </body>
</html>

Once the layout component has been defined, a Blade view can utilize the component.

<!-- resources/views/greetings.blade.php -->
<x-layout>
  <x-slot name="title">
      Greetings
  </x-slot>

  Hello, {{ $name }}
</x-layout>

Template Inheritance

Template Inheritenceopen in new window can be used to create Blade layouts and was the primary way of creating layouts before the introduction of components.

Start by defining a new Blade view to service a template. While this file may be store anywhere in the /resources/views directory, it is a convention to store it in the /resources/views/layouts directory.

<!-- resources/views/layouts/app.blade.php -->
<html>
    <head>
        <title>@yield('title')</title>
        <link rel="stylesheet" href="/app.css">
    </head>
    <body>
        @yield('content')
    </body>
</html>

Once the layout view has been defined, the child view will use the @extends Blade directive to specify which layout the child view should "inherit." Views that extend a Blade layout may inject content into the layout's sections using @section directives.

<!-- resources/views/greetings.blade.php -->

@extends('layouts.app')

@section('title', 'Greetings')

@section('content')
  Hello, {{ $name }}
@endsection