LARAVEL

Laravel Blade Template


Laravel Blade is a templating engine that comes with the Laravel PHP framework. Blade provides a convenient way to write dynamic, reusable views in your Laravel application. Here are some key features and syntax elements of Laravel Blade templates:

 

Variable Output:

  • To output a variable's value, use double curly braces: {{ $variable }}.

 

Raw Output:

  • To output a variable without escaping HTML entities, use {!! $variable !!}.

 

Control Structures:

Blade supports common control structures like @if, @else, @elseif, @unless, @for, @foreach, and @while.

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

 @unless($condition)
     // Code to execute unless the condition is true
 @endunless

 @for($i = 0; $i < 5; $i++)
     // Code to repeat for each iteration
 @endfor

 @foreach($items as $item)
     // Code to execute for each item in the array
 @endforeach

 @while($condition)
     // Code to execute while the condition is true
 @endwhile

 

Including Sub-Views:

  • Use @include('view.name') to include another Blade view within the current view.

 

Extending Layouts:

Define a master layout using @extends('layout.name') and include content sections using @section('sectionName') and @endsection.

 @extends('layouts.app')

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

 

Blade Components:

Blade components allow you to create reusable UI elements. You can define a component using @component and @endcomponent.

 @component('alert')
     // Content of the alert component
 @endcomponent

 

Blade Directives:

Blade has several built-in directives for common tasks, such as @csrf, @auth, @guest, @can, and more.

 @csrf // Generates a hidden CSRF token field
 @auth
     // Code to execute if the user is authenticated
 @endauth

 @guest
     // Code to execute if the user is a guest
 @endguest

 @can('ability')
     // Code to execute if the user has the specified ability
 @endcan

 


LARAVEL