DEV Community

Cover image for Laravel Blade Templating: From Basics to Advanced Techniques
MK
MK

Posted on • Originally published at techtales.blog on

Laravel Blade Templating: From Basics to Advanced Techniques

When it comes to the dynamic world of web development, efficient and readable code is key to success. Laravel, a powerful PHP framework, offers a compelling templating engine known as Blade. In this guide, we delve into the nuances of Laravel Blade Templating, offering insights and code examples to elevate your development skills.

Understanding Laravel Blade Templating

Laravel Blade is more than just a templating engine; its a powerful tool for rendering PHP in a simple and elegant manner. Unlike traditional PHP templates, Blade views are compiled into plain PHP code and cached until they are modified, leading to improved performance.

Basic Concepts of Blade Templating: Syntax and Structure Understanding Blade starts with its syntax, which is designed to be simple yet powerful:

  • Echoing Data: Blades {{ }} syntax automatically escapes output, preventing cross-site scripting (XSS) vulnerabilities.

  • Control Structures: Blade simplifies PHP control structures with directives. For example, @if, @elseif, @else, @endif for conditional statements, and @foreach, @for, @while for loops, making the code cleaner and more readable.

  • Including Subviews: Blades @include directive helps in modularizing the view by allowing the inclusion of smaller view fragments, enhancing reusability and organization.

Basic Syntax of Blade Templating

The Blade syntax is intuitive and easy to learn. Heres a basic example to get started:

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

        <div class="container">
            <h1>Hello, {{ $name }}</h1>
            @yield('content')
        </div>
    </body>
</html>

Enter fullscreen mode Exit fullscreen mode
  • @yield('title'): Used to display the contents of a section.

  • @section('sidebar'): Defines a section named 'sidebar'.

  • {{ $name }}: Echoes content with PHP.

  • @show: Renders the section content.

Working with Conditional Statements

Blade makes it straightforward to use conditional statements:

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif

Enter fullscreen mode Exit fullscreen mode

@if, @elseif, @else: Blade's conditional directives.

Switch statements

@switch($role)
    @case('admin')
        <p>Admin User</p>
        @break
    @default
        <p>Regular User</p>
@endswitch

Enter fullscreen mode Exit fullscreen mode

Loop Structures in Blade

Looping is a breeze with Blade. Heres a quick look at a @foreach loop:

@foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach

Enter fullscreen mode Exit fullscreen mode

@foreach: Iterates over an array or collection.

Integrating Blade with Laravel Controllers

Blades real power shines when integrated with Laravel controllers. For example:

// In a Laravel Controller
public function show($id)
{
    $user = User::findOrFail($id);

    return view('user.profile', ['user' => $user]);
}

Enter fullscreen mode Exit fullscreen mode

In the Blade view, you can display the users name like this:

<h1>Hello, {{ $user->name }}</h1>
Enter fullscreen mode Exit fullscreen mode

Advanced Blade Features and Techniques

Blades capabilities extend to more complex scenarios:

  • Template Inheritance: Blades layout system, with @extends and @section directives, facilitates the reuse of common layout components, reducing duplication.

  • Blade Components and Slots: Introduces a component-based architecture to Blade, allowing for encapsulation and reuse of UI elements.

  • Service Injection: The @inject directive injects services directly into templates, offering a convenient way to access Laravel's service container.

  • Extending Blade: Laravel allows the addition of custom directives to Blade, enabling the creation of domain-specific language (DSL) within templates.

Template Inheritance and Layouts

Blade allows you to define a master layout and extend it in child templates.

Master Layout:

<!-- 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>

Enter fullscreen mode Exit fullscreen mode

Extending a Layout:

@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

Enter fullscreen mode Exit fullscreen mode

Components and Slots:

<!-- components/alert.blade.php -->
<div class="alert alert-{{ $type }}">
    {{ $slot }}
</div>

Enter fullscreen mode Exit fullscreen mode

Usage

<x-alert type="danger">
    This is a danger alert!
</x-alert>

Enter fullscreen mode Exit fullscreen mode

Service Injection:

@inject('metrics', 'App\Services\MetricsService')
<p>Monthly Revenue: {{ $metrics->monthlyRevenue() }}</p>

Enter fullscreen mode Exit fullscreen mode

Custom Directives: Custom directives add immense flexibility. Heres how to create a simple directive:

Blade::directive('datetime', function ($expression) {
    return "<?php echo with{$expression}->format('m/d/Y H:i'); ?>";
});

Enter fullscreen mode Exit fullscreen mode

Usage:

@datetime($date)
Enter fullscreen mode Exit fullscreen mode

Summary:

The Laravel Blade Templating Engine is a cornerstone of the Laravel framework, offering an expressive and elegant way to create dynamic web pages. Its combination of simplicity, power, and extensibility makes it an invaluable tool for Laravel developers.

Top comments (0)