avatarREUBEN SHUMBA

Summary

The provided content is a comprehensive guide on using Laravel Blade, a powerful templating engine within the Laravel framework, which facilitates the creation of dynamic web pages through layouts, data passing, control structures, and custom extensions.

Abstract

The article "Understanding Laravel Blade and How To Use It" offers an in-depth exploration of Laravel Blade, the default templating engine for Laravel. It explains how Blade allows developers to write HTML code with embedded PHP expressions and use features like layouts, data passing, and control structures to create reusable and efficient web page templates. The guide begins with an introduction to Laravel Blade, detailing its benefits such as improved code organization, performance, and readability. It then proceeds to demonstrate how to set up a Laravel project, create Blade views, and render them using routes or controllers. The article further illustrates the use of layouts with the @extends and @section directives, the passing of data to views, and the implementation of control structures within Blade templates. Additionally, it covers the creation of custom directives and components to extend Blade's functionality, providing examples and code snippets for practical understanding. The author emphasizes the importance of Blade's features in streamlining the development process and enhancing the styling capabilities of Laravel applications.

Opinions

  • The author believes that Laravel Blade significantly enhances code organization and performance due to its ability to encapsulate functions and cache compiled PHP code.
  • The article suggests that Blade's directives and helpers make code more readable and expressive.
  • The author indicates that using layouts and components can reduce code duplication and improve the maintainability of Laravel applications.
  • The guide expresses the view that passing data to views and using control structures within Blade templates is straightforward and effective for creating dynamic content.
  • The author encourages the use of custom extensions to tailor Blade to specific project needs, showcasing the framework's flexibility and extensibility.
  • The article concludes with a call to action for readers to follow the author for more Laravel tutorials, indicating the author's commitment to sharing knowledge and contributing to the Laravel community.

Understanding Laravel Blade and How To Use It

Edited via Canva

Introduction

Laravel Blade is a powerful templating engine that lets you use PHP features in your HTML code. It also helps you organize your code into reusable modules, encapsulate functions, and improve performance. In this article, you will learn how to use Laravel Blade to create dynamic web pages with layouts, data, control structures, and custom extensions.

What is Laravel Blade?

Laravel Blade is the default templating engine for the Laravel framework. It allows you to write HTML code with embedded PHP expressions, variables, loops, conditional statements, and other features. Blade files have the .blade.php extension and are stored in the resources/views directory of your Laravel project.

Blade views are compiled into plain PHP code and cached until modified, making them fast and efficient. Blade also provides several directives and helpers that make your code more readable and expressive.

How to Use Laravel Blade?

To use Laravel Blade, you must have a Laravel project set up and running. You can create a new Laravel project using Composer:

composer create-project laravel/laravel my-app

Then, you can serve your application using the php artisan serve command and access it in your browser.

To create a Blade view, you need to create a file with the .blade.php extension in the resources/views directory. For example, you can create a file called welcome.blade.php with the following content:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Blade</title>
</head>
<body>
    <h1>Welcome to Laravel Blade</h1>
    <p>This is a simple Blade view.</p>
</body>
</html>

To render a Blade view, you need to use the view helper function in your routes or controllers. For example, you can create a route in the routes/web.php file that returns the welcome view:

Route::get('/', function () {
    return view('welcome');
});

Now, if you visit the / URL, you will see the welcome view in your browser.

How to Use Layouts, Data, and Control Structures in Laravel Blade?

One of the main benefits of Laravel Blade is that it allows you to create layouts, pass data, and use control structures in your views.

Layouts

Layouts are Blade views that contain common elements of your web pages, such as headers, footers, navigation bars, etc. You can create a layout file in the resources/views directory and use the @extends directive to specify which layout a child view should use. For example, you can create a file called layout.blade.php with the following content:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Blade - @yield('title')</title>
</head>
<body>
    <div class="container">
        @yield('content')
    </div>
</body>
</html>

The @yield directive defines a section that will be filled by the child view. You can use the @section directive in the child view to define the content of the section. For example, you can create a file called about.blade.php with the following content:

@extends('layout')

@section('title', 'About')

@section('content')
    <h1>About Laravel Blade</h1>
    <p>Laravel Blade is a powerful templating engine.</p>
@endsection

The @extends directive indicates that the about view extends the layout view. The @section directive defines the content of the title and content sections. The @endsection directive closes the section. You can also use the @stop or @show directives instead of @endsection.

To render the about view, you need to use the view helper function in your routes or controllers. For example, you can create a route in the routes/web.php file that returns the about view:

Route::get('/about', function () {
    return view('about');
});

Now, if you visit the /about URL, you will see the about view with the layout view applied.

Data

Data are variables or arrays that you can pass from your routes or controllers to your views. You can use the with method or the second argument of the view helper function to pass data to your views. For example, you can pass a name variable to the welcome view:

Route::get('/', function () {
    return view('welcome')->with('name', 'John');
});

Or:

Route::get('/', function () {
    return view('welcome', ['name' => 'John']);
});

You can access the data in your views using the {{ }} syntax, which will echo the data after escaping any HTML characters. For example, you can modify the welcome.blade.php file to display the name variable:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Blade</title>
</head>
<body>
    <h1>Welcome to Laravel Blade, {{ $name }}</h1>
    <p>This is a simple Blade view.</p>
</body>
</html>

Now, if you visit the / URL, you will see the welcome view with the name variable displayed.

You can also use the {!! !!} syntax to display the data without escaping any HTML characters. This is useful if you want to display HTML code from your data. However, you should be careful with this syntax, as it may expose your application to cross-site scripting (XSS) attacks. For example, you can pass an html variable to the welcome view:

Route::get('/', function () {
    return view('welcome', ['html' => '<strong>Hello</strong>']);
});

And display it using the {!! !!} syntax:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Blade</title>
</head>
<body>
    <h1>Welcome to Laravel Blade, {!! $html !!}</h1>
    <p>This is a simple Blade view.</p>
</body>
</html>

Now, if you visit the / URL, you will see the welcome view with the html variable displayed as HTML code.

Control Structures

Control structures are PHP statements that control the flow of your code, such as if, else, elseif, switch, case, for, foreach, while, etc. You can use these statements in your views using the @ prefix. For example, you can use the @if directive to conditionally display some content in your views:

@if($name == 'John')
    <p>You are John.</p>
@elseif($name == 'Jane')
    <p>You are Jane.</p>
@else
    <p>You are not John or Jane.</p>
@endif

You can also use the @unless directive to display some content unless a condition is true:

@unless($name == 'John')
    <p>You are not John.</p>
@endunless

You can use the @switch directive to switch between multiple cases:

@switch($name)
    @case('John')
        <p>You are John.</p>
        @break
    @case('Jane')
        <p>You are Jane.</p>
        @break
    @default
        <p>You are not John or Jane.</p>
@endswitch

You can use the @for directive to loop through a range of numbers:

@for($i = 0; $i < 10; $i++)
    <p>The current value is {{ $i }}</p>
@endfor

You can use the @foreach directive to loop through an array:

@foreach($users as $user)
    <p>The current user is {{ $user->name }}</p>
@endforeach

You can use the @while directive to loop while a condition is true:

@php
    $i = 0;
@endphp
@while($i < 10)
    <p>The current value is {{ $i }}</p>
    @php
        $i++;
    @endphp
@endwhile

You can also use the @break and @continue directives to break or continue a loop:

@foreach($users as $user)
    @if($user->name == 'John')
        @break
    @endif
    <p>The current user is {{ $user->name }}</p>
@endforeach
@foreach($users as $user)
    @if($user->name == 'John')
        @continue
    @endif
    <p>The current user is {{ $user->name }}</p>
@endforeach

How to Create Custom Extensions in Laravel Blade?

Laravel Blade also allows you to create your own custom directives and components to extend its functionality.

Custom Directives

Custom directives are custom keywords that you can define and use in your views. You can create custom directives using the Blade::directive method in the app/Providers/AppServiceProvider.php file.

Create a Custom Directive:

  • Open your AppServiceProvider.php file (located in the app/Providers directory).
  • In the boot method, use the Blade::directive method to define your custom directive. For example, you can create a custom directive called @hello that displays a greeting message:
<?php

namespace App\Providers;

use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Blade::directive('hello', function ($expression) {
            return "<?php echo 'Hello, ' . $expression; ?>";
        });
    }
}
  • Replace 'hello' with your desired directive name and provide the logic inside the closure.

Use Your Custom Directive:

  • In your Blade views, you can now use the @hello directive. For instance:
<p>@hello('world')</p>

This will render as:

Hello, world

Custom Components

Blade components allow you to create reusable UI elements. You can define your own custom components and use them across your application. Here’s how to get started:

Create a Custom Component:

  • Create a new Blade component using the php artisan make:component command. For example:
php artisan make:component MyButton
  • This will generate a MyButton.php file in the View/Components directory.

Define the Component Logic:

  • Inside MyButton.php, define the component’s logic. You can set properties, handle actions, and render the HTML.
  • Example:
public function render() {     return view('components.my-button'); }

Create the Blade View for the Component:

  • Create a Blade view file named my-button.blade.php in the resources/views/components directory.
  • Customize the HTML structure for your button component.

Use Your Custom Component:

  • In any Blade view, you can include your custom component using the <x> syntax:
<x-my-button label="Click me"></x-my-button>
  • The label attribute will be passed to your component.

Stay tuned!!! I will be back with some more cool Laravel tutorials in the next article. I hope you liked the article. Don’t forget to follow me 😇 and give some claps 👏. And if you have any questions feel free to comment. Thank you.

Thanks a lot for reading till the end. Follow or contact me via: Email: [email protected] LinkedIn: https://www.linkedin.com/in/reuben-shumba-a72aaa157/ BuyMeCoffee: https://www.buymeacoffee.com/reubenshumba REUBEN SHUMBA

Laravel
Laravel Framework
Blade Templating Engine
PHP
Web Development
Recommended from ReadMedium