How To Use Blade Templating Engine In Laravel 11

Blade is a powerful templating engine provided by Laravel, designed to simplify the process of creating views. Here’s how you can use Blade templating engine in Laravel 11:

1. Blade Syntax:

Blade provides a simple and expressive syntax to work with. It uses curly braces to echo out variables, and @ symbols to denote directives. For example:

{{-- Echoing variables --}}
{{ $variable }}

{{-- Using directives --}}
@if($condition)
    // do something
@endif

2. Blade Layouts:

Layouts allow you to define the structure of your application’s pages in a single file and include dynamic content within them. You can create a layout file (layout.blade.php) and use @yield to define sections where content will be inserted.

<!-- layout.blade.php -->
<html>
    <head>
        <title>@yield('title')</title>
    </head>
    <body>
        @yield('content')
    </body>
</html>

3. Extending Layouts:

In your views, you can extend the layout and inject content into specific sections using @extends and @section directives.

<!-- home.blade.php -->
@extends('layout')

@section('title', 'Home Page')

@section('content')
    <div>Welcome to the home page!</div>
@endsection

4. Blade Components:

Components are reusable, encapsulated view partials that can be used across multiple pages. You can create components using the @component directive.

<!-- alert.blade.php -->
@component('components.alert')
    @slot('type', 'success')
    {{-- Slot for the content --}}
    Welcome back!
@endcomponent

5. Blade Directives:

Blade provides a variety of directives for flow control, including @if, @else, @foreach, and @while. These directives make it easy to work with PHP logic within your views.

6. Blade Includes:

You can include partial views or components using @include.

@include('partials.sidebar')

Conclusion:

Blade templating engine in Laravel 11 offers a clean and efficient way to work with views, allowing you to create dynamic, reusable components and layouts easily. By mastering Blade, you can streamline your development process and create beautiful, maintainable views for your Laravel applications.

Leave a Reply