Laravel Blade Templates


Laravel Blade Templates – The Laravel Blade Templates is used to add essentially zero overhead to your application. Blade view files use the .blade.php file extension and stored in resources/views directory.


Laravel Blade Templates.

Let us understand how to use laravel Blade Templates.

Function:-

There are some followings function available in laravel Blade Templates.

  • 1. Introduction.
  • 2. Template Inheritance.
  • 3. Components & Slots.
  • 4. Displaying Data.
  • 5. Control Structures.
  • 6. Including Sub-Views.
  • 7. Stacks.
  • 8. Service Injection.
  • 9. Extending Blade.

1. Introduction.

It is a powerful templating engine which is provided with Laravel. Blade template engine does not restrict you from using plain php code in your views but the file will be must save in .blade.php extension. and stored in resource/views directory.

2. Template Inheritance.

Defining A Layout

Lets take a look i am going to define a layout. It is convenient to define this layout as a single blade view.

Let’s look at a simple example.

<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>

As you can see, we use two directive @section and @yield. The @section directive define a section of content. While the @yield is used to display the content of given section.

Extending A Layout

When we use child view, use the blade @extends directive which specify the layout the child view should inherit

@extends('layouts.app')

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

@section('sidebar')
    @parent

    <p>This is appended to the master sidebar.</p>
@endsection

@section('content')
    <p>This is my body content.</p>
@endsection

Route Path:-

Route::get('blade', function () {
    return view('child');
});

3. Components & Slots.

Components and slots provide similar benefits to section and layouts.

<div class="alert alert-danger">
    {{ $slot }}
</div>

The {{ $slot }} variable will contain the content we want to inject into the component.

@component('alert')
    <strong>Whoops!</strong> Something went wrong!
@endcomponent

Sometimes it is helpfull to define multiple slots for a component.

<div class="alert alert-danger">
    <div class="alert-title">{{ $title }}</div>

    {{ $slot }}
</div>

We may inject content into the named slot using the @slot directive.

@component('alert')
    @slot('title')
        Forbidden
    @endslot

    You are not allowed to access this resource!
@endcomponent

Passing Additional Data To Components

Sometimes you have to need to pass additional data to a component. You can also pass an array of data as the second argument to the @component directive.

@component('alert', ['foo' => 'bar'])
    ...
@endcomponent

4. Displaying Data.

You can display data passed to your blade views by taking the variable in curly braces.

Route path:-

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

View part:-

Hello, {{ $name }}.

Displaying Unescaped Data

By default, this {{ }} statement are automatically sent through php function to prevent XSS attacks. If you do not want to escaped your data you can use like this:-

Hello, {!! $name !!}

Blade & JavaScript Frameworks

It also uses the curly braces to indicate the given expression should be displayed in a browser. You can also use the @ symbol to inform the Blade rendering engine an expression should remain untouched.

<h1>Laravel</h1>

Hello, @{{ name }}

The @ symbol will be removed by blade.

The @verbatim Directive

If javascript variable are displaying in a large portion of your template. You can take the HTML in the @verbatim directive.

@verbatim
    <div class="container">
        Hello, {{ name }}.
    </div>
@endverbatim

5. Control Structures.

Blade provides shortcuts for common PHP control structures, like conditional statement and loops.

If Statement

You can construct if statements using the @if, @elseif, @else and @endif directive.

Let’s look at a simple example.

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif

Blade also provide @unless directive.

@unless (Auth::check())
    You are not signed in.
@endunless

The @isset and @empty directive is used to shortcuts for their PHP function.

@isset($records)
    // $records is defined and is not null...
@endisset

@empty($records)
    // $records is "empty"...
@endempty

Loops

Blade also provides simple directive for working with PHP loop structure in conditional statements.

Let’s look at a simple example.

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

@foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach

@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse

@while (true)
    <p>I'm looping forever.</p>
@endwhile

When using loops you can also end the loop or skip the current iteration

Let’s look at a simple example.

@foreach ($users as $user)
    @if ($user->type == 1)
        @continue
    @endif

    <li>{{ $user->name }}</li>

    @if ($user->number == 5)
        @break
    @endif
@endforeach

You can also include the condition with the directive declaration in one line.

@foreach ($users as $user)
    @continue($user->type == 1)

    <li>{{ $user->name }}</li>

    @break($user->number == 5)
@endforeach

The Loop Variable

A $loop variable will be available inside of your loop. This variable provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop

Let’s look at a simple example.

@foreach ($users as $user)
    @if ($loop->first)
        This is the first iteration.
    @endif

    @if ($loop->last)
        This is the last iteration.
    @endif

    <p>This is user {{ $user->id }}</p>
@endforeach

If you are in nested loop then you can access the parent loops.

@foreach ($users as $user)
    @foreach ($user->posts as $post)
        @if ($loop->parent->first)
            This is first iteration of the parent loop.
        @endif
    @endforeach
@endforeach

The $loop variable also contains a variety of other properties.

Comments

You can also pass the comment in view part like this:-

{{-- This comment will not be present in the rendered HTML --}}

6. Including Sub-Views.

Blade’s @include directive allows you to include a blade view from within another view.

<div>
    @include('shared.errors')

    <form>
        <!-- Form Contents -->
    </form>
</div>

By using include method we will inherit all data available in the parent view.

 @include('view.name', ['some' => 'data'])  

If you want to include a include a view that may or may not be present, then you should use the @includeif directive.

@includeIf('view.name', ['some' => 'data']) 

7. Stacks.

Its allows you to push to named stacks which can be rendered somewhere else in another view.

@push('scripts')
    <script src="/example.js"></script>
@endpush 

You can push to a stack as more time as needed.

<head>
    <!-- Head Contents -->

    @stack('scripts')
</head>

8. Service Injection.

The @inject directive can be used to access a service from the laravel Service Container. The first argument passed to @inject is name of the variable and second argument is class or interface name of service which is you want to resolve.

@inject('metrics', 'App\Services\MetricsService')

<div>
    Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
</div>

9. Extending Blade.

Blade allow you to define your own custom directive by using directive method.

Let’s look at a simple example.

<?php

namespace App\Providers;

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

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Blade::directive('datetime', function ($expression) {
            return "<?php echo ($expression)->format('m/d/Y H:i'); ?>";
        });
    }
    public function register()
    {
        //
    }
}

Advertisements

Add Comment

đź“– Read More