Create New Post

Laravel - Blade Templates

Laravel's Blade templating engine is a powerful and intuitive tool for working with PHP views. Blade provides a convenient and clean syntax for common PHP tasks, and it also adds some additional features to make your views more expressive and readable.

Here are some key features of Blade templates in Laravel:

1. Echoing Data:

You can echo data in Blade using the {{ }} syntax:

 <p>{{ $variable }}</p>

2. Raw Output:

If you need to display raw, unescaped data, you can use the {!! !!} syntax:

<p>{!! $rawHtml !!}</p>
 

3. Blade Comments:

You can add comments to your Blade views using the {{-- --}} syntax:

{{-- This is a Blade comment --}}
 

4. Control Structures:

Blade supports common control structures like if, else, elseif, foreach, and forelse:

@if($condition)
    // Code to execute if condition is true
@elseif($anotherCondition)
    // Code to execute if anotherCondition is true
@else
    // Code to execute if none of the conditions are true
@endif

@foreach($items as $item)
    // Loop through items
@endforeach
 

5. Include & Extend:

Blade allows you to include other Blade views using @include and create layouts using @extends:

@extends('layouts.master')

@section('content')
    // Content of the view
@endsection
 

6. Stacks:

Blade provides a convenient way to push to and pop from named stacks:

@push('scripts')
    // Push JavaScript to the 'scripts' stack
@endpush

@stack('scripts')
 

7. Component & Slots:

Laravel 7 and above introduced Blade components and slots, allowing you to create reusable components:

<!-- Alert Component -->
<x-alert>
    <x-slot name="title">Alert Title</x-slot>

    // Alert content
</x-alert>
 

8. Service Injection:

You can inject services directly into your views:

 @inject('service', 'App\Services\SomeService')

<p>{{ $service->method() }}</p>

Laravel - Blade Templates

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

74492