Sling Academy
Home/PHP/Laravel: How to build layouts with Blade

Laravel: How to build layouts with Blade

Last updated: January 15, 2024

Introduction

Laravel’s Blade templating engine provides a simple and yet powerful way to create layouts for web applications. The Blade engine is capable of extending layouts, including partial views, and injecting content into specific sections, which makes it an excellent choice for developers looking to maintain clean and modular codebases. In this tutorial, we’ll journey through the creation of Blade layouts, from basic to advanced concepts, accompanied by illustrative examples.

Understanding Blade Layouts

To truly grasp what Blade layouts are, it’s important to understand that Blade is a templating engine used in Laravel that allows developers to use simple placeholders and directives to build dynamic HTML templates with minimal fuss. A ‘layout’ in Blade serves as a master page which can be extended by other views to create a consistent look and feel across your application.

Let’s start by creating a basic Blade layout:

<!-- resources/views/layouts/app.blade.php -->
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <!-- Add your JavaScript files here -->

    <!-- Styles -->
    <!-- Add your CSS files here -->
</head>
<body>
    <div id="app">
        @yield('content')
    </div>
</body>
</html>

This layout defines a basic HTML document with sections for scripts and styles that you can fill as per your needs. The @yield directive is where the content of sub-views will be “injected”.

Extending a Blade Layout

Now, let’s create a view that extends our app layout:

<!-- resources/views/welcome.blade.php -->
@extends('layouts.app')

@section('content')
    <h1>Welcome to my Laravel app!</h1>
@endsection

When the ‘welcome’ view is rendered, the content under @section(‘content’) will be placed into the @yield(‘content’) section of the layout.

Including Partials

Partials are small chunks of reusable HTML that you can include in other Blade views. Let’s create a navigation bar partial:

<!-- resources/views/partials/nav.blade.php -->
<nav>
    <ul>
        <li><a href="/">Home</a></li>
        <!-- Add other nav items here -->
    </ul>
</nav>

Now, we include this partial in our layout:

<!-- resources/views/layouts/app.blade.php (updated) -->
<body>
    @include('partials.nav')
    <!-- rest of the layout -->
</body>

Advanced Blade Techniques

As applications grow more complex, you may need advanced techniques to manage the layouts. Here are a few advanced Blade features:

Stacks

Stacks allow you to push to named stacks from child views, which can later be rendered in the layout. This is particularly useful for scripts that need to be included at the end of the body tag.

<!-- resources/views/layouts/app.blade.php -->
<!-- rest of the layout -->
@stack('scripts')

In child views, you use the @push directive:

<!-- resources/views/welcome.blade.php (example) -->
@push('scripts')
<script>
    // Some script that will be rendered at the end
</script>
@endpush

Components

Laravel 7 and later introduced Blade components, which are similar to partials but with more functionality, like providing data bindings:

<x-alert type="error" :message="$message" />

Conclusion

In this post, you’ve learned the basics of creating and extending Blade layouts, working with partials, using stacks for scripts, and utilizing Blade components in Laravel. Harnessing the power of Blade, you can build efficient and maintainable templates, contributing to the overall simplicity and elegance of your web application’s structure.

Next Article: Laravel error: Variable undefined in Blade template (4 solutions)

Previous Article: How to Enable/Disable Blade Template Caching in Laravel

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array