Skip to main content

Blade Layouts and Template Inheritance

14/28
Chapter 4 Blade Templating and Frontend Integration

Blade Layouts and Template Inheritance

20 min read Lesson 14 / 28

Blade: Laravel's Powerful Templating Engine

Blade provides a clean, expressive template syntax with zero overhead. Templates are compiled to plain PHP and cached.

The Layout System

Create a master layout:

{{-- resources/views/layouts/app.blade.php --}}
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <title>@yield('title', config('app.name'))</title>
    @vite(['resources/css/app.css', 'resources/js/app.js'])
    @stack('styles')
</head>
<body class="antialiased">
    @include('partials.navigation')

    <main>
        @yield('content')
    </main>

    @include('partials.footer')
    @stack('scripts')
</body>
</html>

Extend it in child views:

{{-- resources/views/posts/index.blade.php --}}
@extends('layouts.app')

@section('title', 'Blog Posts')

@section('content')
    <div class="max-w-4xl mx-auto py-12">
        <h1 class="text-3xl font-bold">Latest Posts</h1>

        @forelse($posts as $post)
            @include('posts.partials.card', ['post' => $post])
        @empty
            <p>No posts yet.</p>
        @endforelse

        {{ $posts->links() }}
    </div>
@endsection

Blade Directives

{{-- Output (auto-escaped) --}}
{{ $post->title }}

{{-- Unescaped output (use carefully) --}}
{!! $post->rendered_body !!}

{{-- Conditionals --}}
@if($post->is_featured)
    <span class="badge">Featured</span>
@elseif($post->is_published)
    <span class="badge">Published</span>
@else
    <span class="badge">Draft</span>
@endif

{{-- Authentication --}}
@auth
    <p>Welcome, {{ auth()->user()->name }}</p>
@endauth

@guest
    <a href="{{ route('login') }}">Sign in</a>
@endguest

{{-- Loops --}}
@foreach($posts as $post)
    <p>{{ $loop->iteration }}. {{ $post->title }}</p>
    @if($loop->last)
        <hr>
    @endif
@endforeach

Blade compiles templates into cached PHP files, so there is zero performance penalty for using its syntax.