Laravel Blade Templating

Last Updated: March 8, 2022

Blade is the custom templating engine used in Laravel

Control Structures

There are two types of control structures found on Blade. They are Conditions(Selection) and Loops

Conditions

@if

@if of the blade is similar to the if the statement of the PHP

@if($count == 0)
    Count is zero 
@elseif ($count==1)
    Count is one
@endif

Loop

@for @foreach @while

This works the same as in PHP

@for($i=0;$i<10;$i++)
    Number is {{$i}}} </br>
@endfor

@foreach example

@foreach($students as $student)
  Name is :  {{$student->name}} </br>
@endforeach

@while loop example

@while($student = array_pop($students))
    Name is :  {{$student->name}} </br>
@endwhile

Template Inheritance

The blade allows you to extend other views. So you can modify other views by including them on your current view

You can use @section, @yeild, and @show

First, you define the master layout file

<!-- Stored in resources/views/layouts/master.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>

Then you have the normal view file

@extends('layouts.master')
 
@section('title', 'Page Title')
 
@section('sidebar')
    @@parent
 
    <p>This is appended to the master sidebar.</p>
@stop
 
@section('content')
    <p>This is my body content.</p>
@stop

@extends(‘layouts.master’) tells that contents are getting from resources\views\layouts\master.blade.php to render this view.

@section(‘title’,’Page Title’) can be used to substitute @yield('title') master.blade.php file

@parent overwrite the content of the parent layout or view

View Partials

When you are in view A, you can include view B inside view A

// resources/view/a.blade.php
<div>
    I am from View A
    @include('a',['text'=>"Some Text from View B"])
</div>

// resources/view/b.blade.php
<div>
    I am from View B </br>
    {{text}}
</div>

You can pass data to view B with include statement

Conditionally including view

Laravel blade syntax allows you to include view conditionally using @includeIf

Include a view if it exists

 @includeIf('a',['text'=>"Some Text from View B"])

Include a view if the given variable is true

 @includeIf($user->isAdmin(),'a',['text'=>"Some Text from View B"])

Include the first view that exists from a given array of views

 @includeIf(['common.header','customer.header',['text'=>"Some Text from View B"])

@each

<div>
    I am from View A
    @each('b','c','d')
</div>

// resourcees/view/b.blade.php
<div>
    I am from View B </br>
</div>

// resourcees/view/c.blade.php
<div>
    I am from View C </br>
</div>
// resourcees/view/c.blade.php
<div>
    I am from View D </br>
</div>

Using Stack in Blade Templating

If you want to add CSS files depending on the view you can use the Stack features of the Blade templating engine. This is very difficult to do with include when you have a hierarchy in your views.

First, define the stack in your parent view with @stack

Assume you have the following views in your application

/resources/views/layout.blade.php file has the following code

<html>
<head>
    @stack('Scripts')
</head>
<body>
@section('content')

@endsection
</body>
</html>

/resources/views/job.blade.php view has the following code

Adding style sheet named job.css

@extends('layout')

@push("Scripts")
    <link rel="stylesheet" href="job.css">
@endpush
@section('content')
    <h2>Job</h2>
@stop

/resources/views/job-appy.blade.php view has the following code

In this view, you are adding another style sheet named job-apply.css

@extends('job')

@prepend("Scripts")
    <link rel="stylesheet" href="job-apply.css">
@endprepend

@section('content')
    <h2>Apply</h2>
@stop

Finally, you will have the following output due to Stack in Blade Template

<html>
<head>
    <link rel="stylesheet" href="layout.css">
    <link rel="stylesheet" href="job-apply.css">
    <link rel="stylesheet" href="location.css">
</head>
<body>
    <h2>Apply</h2>
</body>
</html>

View Composers and Service Injection

If you have the same variable to be used in several views in your application, you can use the View Composer

You are going to use categories = Category::all() in two views named places.index and places.show

The first thing you have to do is to add the following code to your boot() of the App\Providers\AppServiceProviders

 public function boot()
    {
      
        View::composer(
            ['places.index', 'places.show'], function ($view) {
            $view->with('key', 'value');
        }
        );
    }

Create a custom class for the composer

You can create a custom class for the composer and this method is good for complex projects

First, you create the composer class

<?php
namespace App\Http\ViewComposers;

use App\Models\Place;
use Illuminate\View\View;

class PlaceComposer
{
    public function compose(View $view)
    {
        $view->with('key','value');
    }
}

Then add the following code to AppServiceProvide class

public function boot()
{
//  Using class based composers...
    View::composer(['place'], PlaceComposer::class);
}
Test